Compare commits

..
7 Commits
Author SHA1 Message Date
gabby addbe53392 engine: add the ollama System One provider
A third decision-engine provider alongside the local SemIf GGUF and the
remote Winnow server: `engine.provider == "ollama"` talks to ollama's
native `/v1/systemone` route via `semif_agent/ollama_systemone.py`.

It reuses the Winnow DecisionRequest -> choice mapping and the same strict
distribution validation over exactly the requested option ids, and adds
the edges only ollama has:

- no `/health`: `warm()` probes `GET /api/version` + `POST /api/show`,
  which also proves the model is pulled and advertises the `decision`
  capability;
- `engine.ollama.context_tokens: 0` follows the model's real `num_ctx`
  from `/api/show`;
- `keep_alive` rides on the request, criteria descriptions use the ollama
  subset `string | null`, and a choice question needs >= 2 options;
- decision models do not generate text, so `generate()` raises
  `EngineUnavailable` (use `llm.provider == "ollama"` for chat).

Every failure is an `EngineUnavailable` (fatal, like the local engine) and
the engine lock still serializes on the single-slot server.

`cli.build_engine` selects it, the setup interview and `--answers` accept
it, and the install plan skips the engine clone/GGUF/tokenizer for it.
Docs, config.example.json, and tests updated.
2026-11-11 02:57:53 +00:00
gabby 894a85ec2d 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.
2026-10-17 23:29:53 +00:00
gabby faebe8a53a voice: wake-word barge-in (interrupt a spoken reply)
While a reply is speaking the wake word is still scored, so the user can
interrupt it. On a wake the daemon aborts the playback, mutes further
speech while the interrupt is captured/handled, and hands the following
command to the front end. A bare "stop"/"cancel" aborts the reply and
drops anything queued behind it; anything else runs as a new command.

- voice_transport: AudioIO.play(pcm, rate, stop_event); SoundDeviceAudio
  streams in ~50 ms chunks and aborts the output stream on a stop.
  VoiceDaemon gains barge_in.{enabled,wait_s,threshold} and the
  on_barge_in(active) callback; speak() drops text while muted and plays
  through the interruptible path.
- gateway/voice: tags the interrupt utterance (raw["barge_in"]),
  classifies stop vs new command (_is_stop_command), drops queued replies
  on stop, and unmutes once handled.
- config: gateway.voice.barge_in block; config.example.json regenerated.
- tests: wake-abort, mute release, threshold gate, stop/new-command
  classification, sentinel preservation.
2026-10-17 16:56:44 +00:00
gabby a8ca65a6e4 config.example.json: regenerate with the gutendex pack 2026-10-17 08:19:00 +00:00
gabby a6b8617562 lxmf: re-announce when an interface or peer comes online
The startup announce fires before AutoInterface finishes its peering
handshake, so it reaches no peer; a peer discovered later (or a link that
recovers) would otherwise wait out the whole `announce_interval`.

Replace the blocking `_stop.wait(interval)` announce loop with a tick loop
that announces on the interval, and also immediately after an interface scan
sees a new online transition (AutoInterface reports `online` only after its
peering wait, and every discovered peer is a fresh interface). Each announce
records its time and a `reason` (startup / interval / peer discovered) on the
`lxmf_announced` trace event; a scan error is traced, never fatal.
2026-10-17 07:35:12 +00:00
gabby ec3e6b1b97 skills: read-only catalog for introspection bodies
An ordinary skill body may not reach into the agent (`ctx.admin` is the
housekeeping-only mutation surface), but a body that reports the agent's own
capabilities legitimately needs to see the tree. Add that sanctioned surface:

- `SkillCatalog` (skills.py): a read-only view — `categories()` (id -> scope
  description) and `skills(category)` (leaf names) — over a live provider.
- `ActionContext.catalog`: supplied by the scheduler as a locked tree snapshot,
  passed to every body.
- The runner now passes `admin` only to the `housekeeping` category (it was
  previously handed to every body despite the documented rule); ordinary bodies
  get `catalog` instead.

Consumed by the essentials pack's new `skills.list_categories` /
`skills.list_skills` seeds. Docs (CODEGEN.md, AGENTS.md, README.md) updated;
tests cover the catalog, the catalog/admin split on the run context, and the
new pack seeds.
2026-10-17 07:34:39 +00:00
gabby ed894bd329 lxmf: Sideband voice messages (transcribe + Piper voice replies)
The LXMF gateway now handles Sideband push-to-talk voice messages end to end.

Inbound: a PTT message carries its audio in LXMF.FIELD_AUDIO
(`[audio_mode, bytes]`); `lxmf_transport.parse_audio_field` normalizes it and
the adapter transcribes it into an ordinary command when
`gateway.lxmf.voice.enabled` is set. HQ Opus/OGG goes through faster-whisper
(requirements/transcribe.txt); non-HQ Codec2 through the optional pycodec2
bindings (requirements/codec2.txt). No microphone stack is needed.

Outbound: a chat that last messaged by voice is answered with a synthesized
voice message when `gateway.lxmf.voice.reply_with_voice` is on (the default).
`voice_transport.build_synthesizer` speaks the reply with Piper and
`voice_transport.pcm_to_opus_ogg` encodes it to OGG/Opus (48 kHz, PyAV's
libopus); `lxmf_transport.audio_fields` attaches it as a Sideband HQ PTT
message, with the reply text as the content so a text-only client still sees
it. The reply mode follows the chat's most recent inbound message. A missing
synthesizer or any synthesis/encode failure is traced and the reply falls back
to text. Deps: requirements/tts.txt (piper-tts + PyAV), still no microphone.

Also make LXMF replies result-only (`LxmfAdapter.result_only`, overridable via
`gateway.lxmf.result_only: false`): send the skill's result line, dropping
scheduler bookkeeping and the `<skill>: ok —` wrapper.

Wiring: new config keys under `gateway.lxmf` (result_only) and
`gateway.lxmf.voice` (reply_with_voice, max_speak_chars, reply_bitrate, tts);
regenerated config.example.json; the setup interview asks how to handle voice
messages and the install plan adds `install_lxmf_tts` (bootstrap installs
requirements/tts.txt and downloads the reply voice); cli anchors the LXMF
voice_dir to .runtime/voice/tts.

Tests cover the audio field shape, the outbound queue, the adapter's
voice-chat tracking and synthesis fallbacks, result-only routing, the
synthesis/encode helpers, and the setup plan. Docs updated.
2026-10-17 04:53:51 +00:00
37 changed files with 4943 additions and 200 deletions

No files matched your search

+282 -44
View File
@@ -116,7 +116,9 @@ scheduler.py no up-front gate: every input is dispatched
recall never skips the actionability guard or feeds the
monotonic-progress guard;
housekeeping meta skills (delete/clear-config/regen/cancel-build)
operate on the tree via `ctx.admin`; new-skill creation is gated by
operate on the tree via `ctx.admin` (mutation); every other body
sees the tree only through the read-only `ctx.catalog`
(`ActionContext.catalog`, an `SkillCatalog`); new-skill creation is gated by
a tri-state mode (`new_skill_creation`: deny/allow/ask, **deny by
default**) with a
per-category override in the category config, with
@@ -186,7 +188,9 @@ skill.py loop: observe -> act -> observe -> assess; the body is a single
a run paused for input is resumed by re-invoking act with the
answer on request.user_input; a
contract variable the runner cannot satisfy pauses BEFORE
act (pre_act), collects it, and re-runs the full path
act (pre_act), collects it, and re-runs the full path;
the run context supplies the read-only `catalog` to every body
and the mutating `admin` only to the housekeeping category
timers.py in-process timer/alarm service (TimerService) owned by the
scheduler and exposed on ActionContext.timers: a single
background thread fires scheduled timers on the host clock,
@@ -195,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
@@ -209,6 +227,16 @@ winnow.py WinnowEngine -> a remote Winnow `/v1/systemone` typed-decision
ids, and generate() via /v1/chat/completions. stdlib urllib; an
internal lock serializes on the single-slot server; every
failure raises EngineUnavailable (fatal, like the local engine)
ollama_systemone.py
OllamaSystemOneEngine -> ollama's native System One
`/v1/systemone` route (`engine.provider == "ollama"`): same
DecisionRequest -> choice mapping and strict distribution
validation, plus ollama's own edges — reachability/warmth via
/api/version + /api/show (model exists, `decision` capability,
real `num_ctx`), request `keep_alive`, `string | null` criteria
descriptions, and no text generation (decision models don't
generate). stdlib urllib; internal lock; every failure raises
EngineUnavailable.
codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill
bodies against CODEGEN.md (real actions via stdlib transports,
data from the runner via ctx.config, never embedded; bodies
@@ -276,7 +304,11 @@ gateway/ messenger COMMAND intake/reply — and nothing else. base.py:
SimplexAdapter — command simplex-chat daemon over its JSON
WebSocket API (lazy `websockets`, allowlist, batching,
structured `/_send`). lxmf.py: LxmfAdapter — LXMF/Reticulum
(lazy `lxmf`), in-process, allowlist + batching. voice.py:
(lazy `lxmf`), in-process, allowlist + batching, plus Sideband
push-to-talk voice commands (transcribe `FIELD_AUDIO` locally
when `gateway.lxmf.voice.enabled`) and voice replies (Piper ->
Opus/OGG back in `FIELD_AUDIO` when `voice.reply_with_voice`).
voice.py:
VoiceAdapter — the local microphone front end (wake word +
speech-to-text + text-to-speech) over the neutral
`semif_agent/voice_transport.py`; no remote peer and no
@@ -337,15 +369,17 @@ simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway
lxmf_transport.py
neutral LXMF (Reticulum) transport: one in-process Reticulum
instance + LXMF router, persisted delivery identity, announce
loop, inbound normalization, outbound send queue. Lazy `RNS`/
`LXMF` imports keep the module stdlib-only. Knows nothing about
the scheduler or the gateway.
loop, inbound normalization (text + the `FIELD_AUDIO`/`AM_*`
Sideband PTT voice payload, via `parse_audio_field`), outbound
send queue. Lazy `RNS`/`LXMF` imports keep the module
stdlib-only. Knows nothing about the scheduler or the gateway.
voice_transport.py
neutral voice transport: a 16 kHz mono capture loop with an
always-on wake word (openWakeWord), VAD endpointing
(webrtcvad, energy fallback), speech-to-text (faster-whisper)
and text-to-speech (Piper) over `sounddevice`; half-duplex
(capture discarded while speaking). Every heavy dep is
and text-to-speech (Piper) over `sounddevice`; half-duplex by
default with optional wake-word barge-in (abort a spoken reply
and listen for an interrupt command). Every heavy dep is
lazy-imported, keeping the module stdlib-only; the engine
interfaces are plain classes so tests inject fakes. Knows
nothing about the scheduler or the gateway.
@@ -647,6 +681,47 @@ CLI, unit tests (24) + integration tests (2).
and one scheduler (`--platform simplex,lxmf|all`). DMs only for the first cut;
groups/attachments/reactions are future work. See "### gateway (messenger
intake)".
- **LXMF voice commands (Sideband push-to-talk)** (Oct 2026): the LXMF gateway
accepts voice messages, so a Sideband PTT send is a command like any other.
Sideband delivers a PTT message with an empty body and the audio in
`LXMF.FIELD_AUDIO` (`[audio_mode, data]`); `lxmf_transport.normalize_message`
extracts it through `parse_audio_field`, which maps the `LXMF.AM_*` modes to a
decode `kind` (`opus_ogg`/`codec2`/`unknown`) and a `codec2_rate`, and the
adapter transcribes it when `gateway.lxmf.voice.enabled` is set. HQ PTT is
Opus/OGG, decoded and transcribed by
`voice_transport.WhisperTranscriber.transcribe_bytes` (no separate decode step;
faster-whisper bundles PyAV); non-HQ Codec2 is decoded to 8 kHz PCM by
`voice_transport.decode_codec2` (the optional `pycodec2` bindings), wrapped in a
WAV, and transcribed the same way. The Opus path needs only faster-whisper
(`requirements/transcribe.txt`) and Codec2 additionally `pycodec2`
(`requirements/codec2.txt`), **not** the microphone voice stack, so the install
plan's `install_transcribe` flag (from `gateway.lxmf.voice.enabled`) drives a
separate bootstrap stage (the Codec2 bindings best-effort, native) and the
`check_requirements` guard stays lxmf-only. Transcription runs on a dedicated
single-slot worker thread (the Reticulum callback thread only enqueues, since
a slow decode would stall the router); a failure, a missing decoder, an
undecodable mode, or a missing transcriber is traced and reported back to the
sender rather than silently dropped, and the audio is transient — never stored
or exposed, exactly like the voice gateway. See "### gateway (messenger
intake)".
- **LXMF voice replies (Piper -> Sideband PTT)** (Oct 2026): a chat that last
messaged by voice is answered with a voice message when
`gateway.lxmf.voice.reply_with_voice` is on (the default): the adapter
synthesizes the reply text with Piper (`voice_transport.build_synthesizer`
from the `voice.tts` block), encodes it to an OGG/Opus container
(`voice_transport.pcm_to_opus_ogg` resamples to 48 kHz and muxes with PyAV's
bundled libopus), and the transport sends it back in `LXMF.FIELD_AUDIO` as a
Sideband HQ PTT message (`lxmf_transport.audio_fields` ->
`[AM_OPUS_OGG, ogg]`), with the reply text as the message content so a
text-only client still sees it. The reply *mode* follows the chat's most
recent inbound message — a text message reverts it to text replies. Synthesis
runs on the outbound pump thread (never the Reticulum callback thread); it
needs `piper-tts` + PyAV (`requirements/tts.txt`), never the microphone stack,
so the install plan's `install_lxmf_tts` flag (from
`gateway.lxmf.voice.reply_with_voice`) drives its own bootstrap stage. A
missing synthesizer, a synthesis failure, or an encode failure is traced and
the reply falls back to text — never dropped. The reply length is bounded by
`voice.max_speak_chars`. See "### gateway (messenger intake)".
- **Voice gateway (wake word + STT + TTS)** (Oct 2026): `gateway/voice.py`
(`VoiceAdapter`, platform `voice`) is the local microphone front end over the
neutral `semif_agent/voice_transport.py`: an always-on openWakeWord wake word,
@@ -655,11 +730,19 @@ CLI, unit tests (24) + integration tests (2).
single-session routing, `needs_input` questions, repairs, and approvals all
work through `GatewayService` unchanged — a spoken command is just text from
`voice:<chat_id>`, and every reply is spoken. No remote peer and no allowlist
(physical mic access is the authorization). Half-duplex: capture is discarded
while a reply is speaking (no barge-in yet); the wake word is required before
(physical mic access is the authorization). The wake word is required before
every command and is held while the scheduler's single slot is still running
the current request (`GatewayService.input_ready`), so a second command cannot
start until the first reaches a result (or pauses for the user's answer). The
start until the first reaches a result (or pauses for the user's answer).
**Barge-in** (`gateway.voice.barge_in.enabled`, default on): while a reply is
speaking the wake word is still scored, so the user can interrupt — the
playback is aborted (chunked streaming with a `stop_event`; the reply is muted
until the interrupt is handled so it never resumes over the user) and the
following command is captured. A bare "stop"/"cancel" (or a short variant)
aborts the spoken reply and drops anything queued behind it; anything else is
run as a new command. `barge_in.threshold` raises the wake bar for barge-in
only (0 = use `wake.threshold`) so the agent's own TTS cannot self-trigger.
Disable for strict half-duplex. The
whole voice stack is optional and lazy-imported (`requirements/voice.txt`,
pinned separately from the engine set since it is hardware-dependent); the
gateway refuses to start with an install hint. `bootstrap.sh --voice`
@@ -667,6 +750,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
@@ -716,28 +833,45 @@ CLI, unit tests (24) + integration tests (2).
in config.json — the same provider pattern as `llm`/`codegen`. `"semif"`
(default) is the local llama.cpp GGUF (`SemIfEngine`); `"winnow"` is a remote
Winnow `/v1/systemone` typed-decision API (`semif_agent.winnow.WinnowEngine`,
configured by the nested `engine.winnow` block). `cli.build_engine` picks the
class; `SemIfEngine`/`WinnowEngine` both satisfy `engine.DecisionEngine`
(`call`/`warm`/`loaded`/`generate`).
configured by the nested `engine.winnow` block); `"ollama"` is ollama's native
System One `/v1/systemone` route
(`semif_agent.ollama_systemone.OllamaSystemOneEngine`, configured by the
nested `engine.ollama` block). `cli.build_engine` picks the class;
`SemIfEngine`/`WinnowEngine`/`OllamaSystemOneEngine` all satisfy
`engine.DecisionEngine` (`call`/`warm`/`loaded`/`generate`).
- **`winnow` and `ollama` are different edges of the same System One contract.**
Both map the flat decision onto a `choice` question and validate/normalize the
returned distribution over exactly the requested option ids, but the
`ollama` provider implements the deployment details only ollama has: there is
no `/health`, so `warm()` probes `GET /api/version` and `POST /api/show`
(which also proves the model is pulled and advertises the `decision`
capability), `engine.ollama.context_tokens: 0` follows the model's real
`num_ctx` from `/api/show`, `keep_alive` rides on the request, choice criteria
descriptions use the ollama subset `string | null`, and a choice question
needs at least two options. Decision models do not generate text, so
`OllamaSystemOneEngine.generate` raises `EngineUnavailable` — use
`llm.provider == "ollama"` for the chat path.
- **The engine is always real and every `EngineUnavailable` is fatal**,
whichever provider is selected: `WinnowEngine` converts every network, HTTP,
and malformed/unnormalized-distribution failure into `EngineUnavailable` so
the scheduler's fatal path (and the codegen watchdog / LLM bridge's graceful
paths) behave identically to the local engine. There is no fallback model.
whichever provider is selected: `WinnowEngine`/`OllamaSystemOneEngine` convert
every network, HTTP, and malformed/unnormalized-distribution failure into
`EngineUnavailable` so the scheduler's fatal path (and the codegen watchdog /
LLM bridge's graceful paths) behave identically to the local engine. There is
no fallback model.
- The agent's flat decision (`state` + `question` + typed `options`) maps onto
Winnow's `choice` question type (`options` -> `criteria` id->description,
`question` -> `instructions`); the returned distribution is validated against
exactly the requested option ids and normalized. `generate` goes through the
same server's `/v1/chat/completions`, so `llm.provider == "semif"` keeps
working when the decision engine is Winnow.
the System One `choice` question type (`options` -> `criteria`
id->description, `question` -> `instructions`); the returned distribution is
validated against exactly the requested option ids and normalized. For
`winnow`, `generate` goes through the same server's `/v1/chat/completions`, so
`llm.provider == "semif"` keeps working when the decision engine is Winnow.
- Swapping the decision model changes routing/assessment behaviour and the
decision-log distribution; that is the intended per-machine choice. The
decision log and `dream` cost are unchanged because `DecisionResult` is the
same contract.
- Context differs by provider (the local engine's `engine.context_tokens` vs the
remote server's own `--ctx-size`, mirrored in `engine.winnow.context_tokens`);
a state that overflows is a fatal `EngineUnavailable`, the same class as the
local token limit. Every engine exposes its window as `context_tokens` (a
remote server's own decision window, mirrored in `engine.winnow.context_tokens`
or discovered from `engine.ollama`'s `/api/show` `num_ctx`); a state that
overflows is a fatal `EngineUnavailable`, the same class as the local token
limit. Every engine exposes its window as `context_tokens` (a
`DecisionEngine` property), which the scheduler uses to size generated
artifacts — see "Artifact size budget".
@@ -783,8 +917,8 @@ CLI, unit tests (24) + integration tests (2).
which installs the Vulkan build prereqs
(`libvulkan-dev glslc spirv-headers glslang-tools`) when needed. A CPU-only
host keeps the default CPU wheel — a GPU build is slower on CPU. A host whose
`engine.provider` is `"winnow"` installs none of this (no clone, no GGUF, no
tokenizer, no engine deps).
`engine.provider` is `"winnow"` or `"ollama"` installs none of this (no clone,
no GGUF, no tokenizer, no engine deps).
- **Expected pip warnings:** pip reports "dependency conflicts" against
semif-phase1's declared requirements (torch/accelerate/protobuf/sentencepiece
not installed, numpy 2.2.6 vs 2.3.5). These are informational — the staging
@@ -864,7 +998,8 @@ CLI, unit tests (24) + integration tests (2).
a checkout (register its SSH key on your git host first), then run
`scripts/bootstrap.sh`. On a fresh machine it runs the **setup interview**
(`semif_agent/setup.py`, the `cli setup` subcommand) and writes the split
config from the answers — decision engine (local SemIf 4B or remote Winnow),
config from the answers — decision engine (local SemIf 4B, remote Winnow, or
an Ollama System One decision model),
new-skill authoring mode (+ `llm`/`codegen` endpoints when enabled), capability
packs, gateways, and timezone — then installs only what those answers require
(the install *plan* drives every conditional stage). Which packs exist is owned
@@ -878,7 +1013,12 @@ CLI, unit tests (24) + integration tests (2).
`--voice` / `--browser` additionally install those optional stacks
(`requirements/voice.txt` + system `libportaudio2` + `alsa-utils`;
`packs/browser/requirements.txt` + a browser) even when the plan did not pick
them.
them. The plan's `install_transcribe` flag (from `gateway.lxmf.voice.enabled`)
installs `requirements/transcribe.txt` (faster-whisper only) and warms its STT
model, and `install_lxmf_tts` (from `gateway.lxmf.voice.reply_with_voice`)
installs `requirements/tts.txt` (piper-tts + PyAV) and downloads the reply
voice — a rerun picks either up after the operator enables the setting in
config.
The script must be run from a checkout — it reads pins from that checkout's
`pins.json` and never re-clones the agent repo (only the pack index, the
selected packs, the SemIf engine, and the simplex-chat binary). Idempotent and
@@ -906,7 +1046,10 @@ CLI, unit tests (24) + integration tests (2).
`simplex_chat` ports/display names stay in `config.json`. The python dep pins
live in `requirements/` split by concern (committed): `core.txt` (the test
runner, always), `engine.txt` (the local decision engine), `transports.txt`
(websockets/lxmf), plus the optional `voice.txt`; `staging.txt`
(websockets/lxmf), plus the optional `voice.txt` (full microphone stack),
`transcribe.txt` (faster-whisper only), `tts.txt` (piper-tts + PyAV, for LXMF
voice replies) and `codec2.txt` (`pycodec2`, native, for
LXMF Codec2 voice messages); `staging.txt`
is the union of the non-hardware files. A pack owns the deps its skills/bridge
need, shipped at `packs/<name>/requirements.txt` (e.g. the browser pack's
Playwright pin); the install plan lists the selected/enabled packs that ship
@@ -1046,7 +1189,7 @@ CLI, unit tests (24) + integration tests (2).
never holds secrets, and a generated body with the same name replaces the pack
skill. The shipped packs: `nextcloud`, `simplex`, `outlook`, `browser` (each
owning its bridge), and `essentials` (the built-in local utilities `time` +
`calculator`; no bridge). `nextcloud.create_event` is the authoritative worked
`calculator` + `skills`; no bridge). `nextcloud.create_event` is the authoritative worked
example (creates a CalDAV event through the Nextcloud bridge; derives the
title/date/time from the query, asks for
missing fields and resumes, resolves the target calendar with a SemIf choice
@@ -1073,6 +1216,14 @@ CLI, unit tests (24) + integration tests (2).
roots/fractions/percentages, SemIf picks the operands when the request offers
more numbers than the operator consumes, and the answer is spelled out in words
for the ear (an inexact result is announced as "approximately ...");
`skills.list_categories` and `skills.list_skills` are the introspection skills
(`compute` transport, empty contract): they read the agent's own tree through
the read-only `ctx.catalog` (never the housekeeping-only `ctx.admin`) and
report the category list, or the leaf names inside a category named in the
request (asking for one when it is missing, and reporting an unknown category
honestly) — so a voice user can ask "list skill categories" or "list skills in
nextcloud". The closed `response` tree is filtered out of both (it is the
non-request catchall, not a capability);
`tests/test_packs.py` keeps every pack skill honest.
- **Contract provenance.** Each authored body records the CODEGEN.md revision it
was written against. `skill_contract_ref()` (`codegen.py`) returns
@@ -1360,6 +1511,56 @@ CLI, unit tests (24) + integration tests (2).
Reticulum` and `LXMF.LXMRouter` install process signal handlers, which only
work on the main thread** — `run_gateway` calls `daemon.prepare()` on the main
thread before the transport threads start, and `run()` reuses it.
**Voice commands (Sideband push-to-talk).** A Sideband PTT message arrives as
LXMF content with an empty body and the audio in `FIELD_AUDIO`
(`[audio_mode, bytes]`); `lxmf_transport.parse_audio_field` normalizes it into
`{"codec","codec_name","data","kind","codec2_rate"}` (`kind` = the decode path
`opus_ogg`/`codec2`/`unknown`) and the adapter's `_on_item` routes it to
transcription when `gateway.lxmf.voice.enabled` is set, dispatching the
transcript as an ordinary command (same allowlist, same reply path). A
dedicated single-slot `lxmf-voice-worker` thread does the (slow) transcription
off the Reticulum callback thread, which only enqueues; on any failure the
sender gets a transport-level notice (`_notify`) rather than silence. HQ PTT
(`AM_OPUS_OGG`, the default) is decoded by `WhisperTranscriber.transcribe_bytes`
— it needs **only `faster-whisper`** (whose bundled PyAV decodes the Opus/OGG
container), never the microphone voice stack, so `check_requirements` stays
lxmf-only and a missing transcriber degrades gracefully (`voice.enabled` off,
or a traced `lxmf_voice_unavailable`). Non-HQ Codec2 PTT is decoded to 8 kHz
PCM by `voice_transport.decode_codec2` (the optional `pycodec2` bindings,
`requirements/codec2.txt`), wrapped in a WAV by `pcm_to_wav`, and transcribed
the same way; an absent decoder is traced `lxmf_voice_codec2_unavailable` and
reported, and the binding-less 450 modes as `lxmf_voice_unsupported_codec` —
never silently dropped. The audio is transient and never stored, exactly like
the voice gateway.
**Voice replies (Piper -> Opus/OGG).** When `voice.reply_with_voice` is on
(the default), a chat that last messaged by voice is answered with a voice
message: `_voice_reply` (on the outbound pump thread) synthesizes the reply
text with Piper (`voice_transport.build_synthesizer` from `voice.tts`),
encodes it to OGG/Opus with `voice_transport.pcm_to_opus_ogg` (48 kHz, PyAV's
bundled libopus), and `LxmfDaemon.send` attaches it in `FIELD_AUDIO`
(`lxmf_transport.audio_fields` -> `[AM_OPUS_OGG, ogg]`) with the reply text as
the message content (a text-only client still sees it). The reply mode follows
the chat's most recent inbound message — a text message reverts it to text
replies. It needs **only `piper-tts` + PyAV** (`requirements/tts.txt`), never
the microphone stack, so `check_requirements` stays lxmf-only; a missing
synthesizer (`lxmf_voice_tts_unavailable`), a synthesis failure
(`lxmf_voice_synth_failed`), or an encode failure (`lxmf_voice_encode_failed`)
is traced and the reply falls back to text — never dropped. The reply length
is bounded by `voice.max_speak_chars`.
**Result-only output**: `LxmfAdapter.result_only` (default true; per-platform
config `result_only` overrides) makes `GatewayService` send just the skill's
result line — scheduler bookkeeping is dropped and the `<skill>: ok —` wrapper
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
@@ -1385,9 +1586,19 @@ CLI, unit tests (24) + integration tests (2).
phrase's tail, not the command — until `vad.min_command_ms` of speech is in
hand the trailing-silence endpoint uses `vad.initial_silence_ms`, so a natural
pause before the command does not end the capture (then `vad.silence_ms`).
**Half-duplex**: capture frames are discarded while a
reply is speaking, so the agent never transcribes itself (no barge-in yet);
the wake word is required before every command, and is **held while the
**Half-duplex by default, barge-in optional** (`gateway.voice.barge_in`):
capture frames are normally discarded while a reply is speaking, so the agent
never transcribes itself; with `barge_in.enabled` the wake word is still
scored during playback, so the user can interrupt. The daemon's `play` streams
the reply in small chunks and watches a `stop_event`, so a barge-in aborts the
playback promptly; the daemon then mutes speech (`_mute`), tells the front end
via `on_barge_in(True/False)`, and captures the following command.
`barge_in.threshold` (0 = `wake.threshold`) is a separate, usually higher wake
bar for barge-in so the agent's own TTS cannot self-trigger. The
`VoiceAdapter` tags that utterance (`raw["barge_in"]`): a bare "stop"/"cancel"
(`_is_stop_command`) drops any queued replies and unmutes without submitting,
while anything else is run as a new command and unmutes when handled. The wake
word is required before every command, and is **held while the
scheduler slot is busy** (`GatewayService.input_ready`): a wake that fires
while the current request is still running is ignored (traced
`voice_wake_blocked`), so a second command cannot start until the first
@@ -1400,6 +1611,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
@@ -1481,15 +1701,22 @@ CLI, unit tests (24) + integration tests (2).
scheduler, no HTTP.
- **Tests.** `tests/test_gateway.py` (stdlib): SimpleX adapter allowlist/auth,
structured send command, batching (real `asyncio`), LXMF adapter
allowlist/auth and batching (a `threading.Timer`), cross-platform pending-run
guard and per-platform reply routing, and `GatewayService` routing against a
real `Scheduler` (lazy engine, unreachable LLM).
allowlist/auth and batching (a `threading.Timer`), LXMF voice-message
transcription through an injected fake transcriber (Opus dispatch, Codec2
decode/wrap via a stubbed `decode_codec2`, disabled-ignores, unsupported-codec,
missing-Codec2-decoder and failure notices, caption fallback) and LXMF voice
replies through an injected fake synthesizer (voice-chat marking, text-reverts,
`reply_with_voice` off, synthesis-failure fallback, length bound),
cross-platform
pending-run guard and per-platform reply routing, and `GatewayService` routing
against a real `Scheduler` (lazy engine, unreachable LLM).
`tests/test_humanize.py` covers the optional result cleanup with an injected
fake `llm` client (rewrite, quote/whitespace normalization, fallback on
error/empty/runaway, disabled passthrough, and the global +
per-platform gateway enable/disable wiring).
`tests/test_lxmf_transport.py` covers the neutral LXMF transport's
missing-dep contract, default paths, and `normalize_message` (no real `lxmf`
missing-dep contract, default paths, and `normalize_message` (including the
`FIELD_AUDIO`/`AM_*` voice payload via `parse_audio_field`; no real `lxmf`
needed). `tests/test_simplex_ws.py` covers the neutral protocol layer (parse
shapes, accept ids, corrId round-trips, address show/create).
`tests/test_bridges.py`
@@ -1506,8 +1733,14 @@ CLI, unit tests (24) + integration tests (2).
the Nextcloud/Outlook/Browser bridges over a loopback `http.server` with a fake
service or driver).
`tests/test_voice_gateway.py` drives the voice loop
with injected fake engines (wake gating, endpointing, half-duplex,
`speak` truncation/failure, adapter + CLI wiring) — no
with injected fake engines (wake gating, endpointing, half-duplex and
barge-in — wake-abort, mute, stop/new-command classification,
`speak` truncation/failure, adapter + CLI wiring) plus the transcribe-only
helpers (`check_codec2_requirements`, `decode_codec2` over an injected fake
`pycodec2`, `pcm_to_wav`) and the voice-reply helpers
(`check_synthesis_requirements`, `build_synthesizer` over a stubbed
`PiperSynthesizer`, `pcm_to_opus_ogg`'s empty-input contract and, when PyAV is
importable, its OGG/Opus round-trip) — no
hardware, network, or heavy packages. `tests/test_voice_record.py` covers the
recording helpers (`semif_agent/voice_train.py`) — prompt loading, WAV I/O,
level math, the silence-endpointing loop, and the LJSpeech dataset writer —
@@ -1523,6 +1756,10 @@ CLI, unit tests (24) + integration tests (2).
system `libportaudio2` + `alsa-utils`); it is lazy-imported too, and `bootstrap.sh --voice`
installs it and downloads the models (openWakeWord into the venv package dir,
the Piper voice into `.runtime/voice/tts`, faster-whisper into `.runtime/hf`).
The LXMF gateway's transcribe-only and voice-reply paths pin only what they
need (`requirements/transcribe.txt` faster-whisper; `requirements/tts.txt`
`piper-tts` + PyAV; `requirements/codec2.txt` `pycodec2`), never the
microphone stack.
### skill packs (bundles)
@@ -1566,9 +1803,10 @@ CLI, unit tests (24) + integration tests (2).
`packs.<name>`. 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` +
`calculator`; no bridge) — each in its own repository. Adding a concern means
adding a pack repo, not editing `skills.py`.
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`.
### bridges (third-party API services)
+6 -2
View File
@@ -303,8 +303,12 @@ def act(ctx, request) -> ActionResult:
`ctx.config` (the resolved values for this skill, including its own config),
and `ctx.timers` (the in-process timer/alarm service — use it to schedule a
notification, as the `time.set_timer` and `time.set_alarm` seeds do).
`ctx.admin` exists for the built-in housekeeping meta skills only; an ordinary
body must never touch it.
`ctx.catalog` is a **read-only** view of the agent's own skill tree for an
introspection skill that reports what the agent can do: `ctx.catalog.categories()`
returns a `{category_id: description}` map and `ctx.catalog.skills(category)`
the leaf names inside one category (the `skills.list_categories` /
`skills.list_skills` seeds). `ctx.admin` exists for the built-in housekeeping
meta skills only; an ordinary body must never touch it.
- `request` is the `Request` being handled.
- `ActionResult(action_log: str, new_state: str, needs_input: str | None = None,
decisions: list = [])` is imported from `semif_agent.skills`; return that exact
+64 -14
View File
@@ -352,7 +352,9 @@ fine-tuning loop — it is not yet the fine-tune itself.
with prompt hashes, tokens and timing.
- **Run lifecycle tracing** — `runs.jsonl` keyed by `run_id`, powering a
Redux-DevTools-style dashboard.
- **Messenger command gateway (SimpleX + LXMF)** — take commands and reply over DM.
- **Messenger command gateway (SimpleX + LXMF)** — take commands and reply over DM,
including Sideband push-to-talk **voice messages** on LXMF (local transcription,
and voice replies synthesized with Piper).
- **Voice gateway** — a local microphone front end: wake word + speech-to-text +
text-to-speech, all local (openWakeWord / faster-whisper / Piper).
- **Standalone bridge services** — an optional token-guarded localhost HTTP
@@ -361,8 +363,10 @@ fine-tuning loop — it is not yet the fine-tune itself.
- **Seeds** — shipped real starter skills: `nextcloud.create_event` (the
authoritative worked example), `nextcloud.next_event` (the user's Nextcloud
calendar, through the bridge), `nextcloud.create_task` (Nextcloud task list),
`simplex.next_message` / `simplex.send_message` / `simplex.connect_link`, and
`calculator.calculate` (two operands, one SemIf-chosen operator, spoken answer).
`simplex.next_message` / `simplex.send_message` / `simplex.connect_link`,
`calculator.calculate` (two operands, one SemIf-chosen operator, spoken answer),
and `skills.list_categories` / `skills.list_skills` (report the agent's own
skill categories, or the skills inside a named category).
- **Fatal-on-engine-loss** — the engine is always real; its absence exits the app.
- **Stdlib-only core** — SemIf/llama.cpp are lazy imports, so the package stays
importable and testable without the heavy engine installed.
@@ -410,8 +414,11 @@ packs/ skill packs, each cloned from its own repo (pack.<name>)
pack list lives in the semif-packs index repo (see PACKGEN.md)
scripts/ bootstrap.sh, config_merge.py, voice-*.py, systemd/*.in
requirements/ core.txt (test runner), engine.txt (local decision engine),
transports.txt (websockets/lxmf), voice.txt
(staging.txt = the union of the non-hardware files);
transports.txt (websockets/lxmf), voice.txt (microphone
stack), transcribe.txt (faster-whisper, LXMF voice
messages), tts.txt (piper-tts + PyAV, LXMF voice replies),
codec2.txt (pycodec2, LXMF Codec2 PTT);
staging.txt = union of the non-hardware files;
a pack's own deps live with the pack at
packs/<name>/requirements.txt
tests/ stdlib unit tests + tests/integration (real engine + LLM)
@@ -438,13 +445,18 @@ what it needs, based on the answers to a short first-run interview.
### Prerequisites: the decision engine, and optional models
The **decision engine** routes every request. It runs one of two ways, chosen in
the interview:
The **decision engine** routes every request. It runs one of three ways,
chosen in the interview:
- **local** — the pinned SemIf 4B GGUF via llama.cpp (no network). This is the
default and the whole minimum path.
- **remote** — a Winnow `/v1/systemone` decision server (`engine.provider ==
"winnow"`). The local engine clone, GGUF, and tokenizer are then skipped.
- **remote Ollama** — ollama's native System One `/v1/systemone` route
(`engine.provider == "ollama"`) against a pulled decision model. It probes
ollama's `/api/version` + `/api/show`, follows the model's real `num_ctx`, and
skips the local engine clone/GGUF/tokenizer too. System One models do not
generate text, so this provider cannot back `llm.provider == "semif"`.
The local engine is CPU by default; to offload it to a GPU, set
`engine.gpu_layers` in `config.json` and run
@@ -460,7 +472,8 @@ shipped packs. When it is on, two OpenAI-compatible endpoints are required
newly created category/skill. Its `provider` can be `"ollama"` (default),
`"opencode"` (the hosted Console API), or `"semif"` — the already-loaded
decision engine model generates in-process, with no endpoint and no
`llm.model` at all.
`llm.model` at all (the local SemIf or Winnow engine only; an Ollama
System One decision model does not generate text).
- **`codegen`** — a large, code-capable model that writes skill bodies. This is
slow and ideally on a beefier host.
@@ -475,7 +488,8 @@ scripts/bootstrap.sh
On a fresh machine the script **asks a few questions** and writes this machine's
config from the answers:
1. **Decision engine** — local SemIf 4B, or a remote Winnow server (URL/model/key).
1. **Decision engine** — local SemIf 4B, a remote Winnow server, or a remote
Ollama System One decision model (URL/model/key).
2. **Skill authoring** — `deny` (default), `ask`, or `allow`; if enabled, the
`llm` + `codegen` endpoints and credentials.
3. **Capabilities** — the skill packs to enable, offered from the pack index
@@ -489,9 +503,10 @@ It then installs **only what those answers require**. Both ends of the spectrum
are reachable by the end of a run:
- **minimum** — local SemIf 4B + `essentials` (canned replies, time/timers,
calculator). No account, no network, no gateway, no heavy downloads.
- **maximum** — every pack, a remote Winnow engine, remote `llm`/`codegen`
endpoints, and all gateways.
calculator, skill listing). No account, no network, no gateway, no heavy
downloads.
- **maximum** — every pack, a remote Winnow or Ollama System One decision
engine, remote `llm`/`codegen` endpoints, and all gateways.
Non-interactive runs: `--yes` takes the minimum defaults; `--answers FILE`
replays a saved answer set (JSON matching the `setup` fields). The script is
@@ -509,8 +524,10 @@ The script:
4. creates `.runtime/venv` and installs only the needed dep files:
`requirements/core.txt` always, `engine.txt` for a local engine,
`transports.txt` when a SimpleX/LXMF transport is selected (`voice.txt` for
the voice stack, and each selected pack's own `packs/<name>/requirements.txt`
— e.g. the browser pack's Playwright deps);
the voice stack, `transcribe.txt` when `gateway.lxmf.voice` is enabled —
plus `tts.txt` when `voice.reply_with_voice` is on, and `codec2.txt` + system
`libcodec2` best-effort for non-HQ Codec2 PTT — and each selected pack's own
`packs/<name>/requirements.txt` — e.g. the browser pack's Playwright deps);
5. for a local engine, downloads/sha256-verifies the GGUF into `.runtime/models/`
and pre-fetches the HF tokenizer into `.runtime/hf/`;
6. downloads/sha256-verifies the pinned `simplex-chat` binary **only** when a
@@ -583,6 +600,7 @@ Key blocks:
| `queue` | `max_size` |
| `skill_bodies` / `skill_packs` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) |
| `gateway.simplex` | command gateway: ws_url, allowlist, batching |
| `gateway.lxmf` | LXMF gateway: allowlist, Reticulum paths, `result_only` replies, Sideband voice transcription (`voice.enabled` + `voice.stt` model) and voice replies (`voice.reply_with_voice` + `voice.tts` voice) |
| `gateway.voice` | voice gateway: wake/STT/TTS engines + models, audio devices, VAD |
| `bridges.simplex` | forwarding bridge: host/port/token/ws_url |
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
@@ -718,6 +736,32 @@ matches the peer's LXMF address (32 hex) or a best-effort display name.
and an optional `propagation_node` enables store-and-forward. Add the printed
address as a contact in your LXMF client and DM it.
**Voice commands (Sideband push-to-talk).** Set
`gateway.lxmf.voice.enabled: true` and a Sideband PTT voice message is
transcribed into a command, just like typed text. HQ PTT (Opus/OGG) is decoded
and transcribed by faster-whisper, which needs only `requirements/transcribe.txt`
(installed by the install plan — no microphone, no voice stack). Non-HQ Codec2
PTT is decoded by the optional `pycodec2` bindings (`requirements/codec2.txt`,
installed best-effort alongside the system `libcodec2`); without it a Codec2
message is reported back rather than dropped. The audio is transient and never
leaves the machine. The model is `gateway.lxmf.voice.stt.model` (default
`base.en`).
**Voice replies.** With `gateway.lxmf.voice.reply_with_voice: true` (the
default), a chat that last messaged by voice is answered with a synthesized
voice message: the reply text is spoken with Piper and sent back as a Sideband
HQ push-to-talk message, with the text also carried as the message content so a
text-only client still sees it. A later text message from that chat reverts it to
text replies. This needs only `piper-tts` + PyAV (`requirements/tts.txt`,
installed by the install plan — still no microphone); a missing stack or a
synthesis failure falls back to a text reply rather than dropping it. The voice
is `gateway.lxmf.voice.tts.voice` (default `en_US-lessac-medium`).
**Result-only replies.** The LXMF gateway sends only the skill's result line:
the scheduler's queue/urgency bookkeeping is dropped and the `<skill>: ok —`
wrapper is stripped, so a DM is the answer, not the internals. Override with
`gateway.lxmf.result_only: false` for the full scheduler output.
> **Gateway isolation is non-negotiable.** The gateway takes commands and sends
> replies — nothing else. It never reads history, shows or creates invite links,
> or composes messages. That is messaging UX and lives in the bridges.
@@ -1028,6 +1072,12 @@ authoring a new pack (and a new bridge to back one).
cubes, square roots, cube roots, fractions, and percentages, and SemIf picks
the operands when the request writes more numbers than the operation needs
(pure local compute, no config).
- `skills.list_categories` — list the categories of skills the agent has
(pure local compute, no config; reads the read-only `ctx.catalog`, not the
housekeeping-only `ctx.admin`).
- `skills.list_skills` — list the skills inside a category named in the request
("list skills in nextcloud"), asking for one when it is missing and reporting
an unknown category honestly (pure local compute, no config).
---
+49 -2
View File
@@ -39,6 +39,17 @@
"user_agent": "semif-agent",
"extra_headers": {}
},
"ollama": {
"base_url": "http://127.0.0.1:11434",
"model": "",
"context_tokens": 16384,
"api_key": "!secret engine_ollama_api_key",
"timeout": 120,
"retries": 0,
"keep_alive": "",
"user_agent": "semif-agent",
"extra_headers": {}
},
"gguf": ""
},
"llm": {
@@ -157,7 +168,31 @@
"storage_path": "",
"home_channel": "",
"reply_prefix": "",
"text_batch_delay": 0.8
"text_batch_delay": 0.8,
"result_only": true,
"voice": {
"enabled": false,
"reply_with_voice": true,
"max_speak_chars": 600,
"reply_bitrate": 24000,
"read": {
"enabled": true,
"chunk_chars": 300
},
"stt": {
"model": "base.en",
"device": "cpu",
"compute_type": "int8",
"language": "en"
},
"tts": {
"voice": "en_US-lessac-medium",
"voice_dir": "",
"speaker_id": 0,
"length_scale": 1.0,
"volume": 1.0
}
}
},
"voice": {
"enabled": false,
@@ -167,6 +202,10 @@
"reply_prefix": "",
"result_only": true,
"max_speak_chars": 600,
"read": {
"enabled": true,
"chunk_chars": 300
},
"listen_timeout_s": 3.0,
"cue": {
"enabled": true,
@@ -226,7 +265,12 @@
"aggressiveness": 2,
"energy_threshold": 200.0
},
"follow_up_window_s": 0.0
"follow_up_window_s": 0.0,
"barge_in": {
"enabled": true,
"wait_s": 2.0,
"threshold": 0.0
}
}
},
"dashboard": {
@@ -306,6 +350,9 @@
"packs": {
"essentials": {
"enabled": true
},
"gutendex": {
"enabled": true
}
}
}
+9
View File
@@ -175,6 +175,15 @@ Then on the gateway host set:
"gateway": { "voice": { "tts": { "voice": "<name>" } } }
```
The LXMF gateway's voice replies resolve a Piper voice the same way from
`.runtime/voice/tts/` (`cli._build_gateway_adapter` anchors
`gateway.lxmf.voice.tts.voice_dir` there too), so the same trained voice can back
both the microphone gateway and Sideband push-to-talk replies:
```json
"gateway": { "lxmf": { "voice": { "tts": { "voice": "<name>" } } } }
```
Restart the gateway and speak a reply. **Only a real spoken reply proves the
integration** — a generated test passing proves mechanics, not that the voice
loads and sounds right.
+15
View File
@@ -0,0 +1,15 @@
# Codec2 voice-message decoding (optional).
#
# Sideband's non-HQ push-to-talk messages carry raw Codec2 frames
# (`LXMF.AM_CODEC2_*`); decoding them needs the `pycodec2` bindings, which
# compile against the system `libcodec2` (Debian/Ubuntu: `libcodec2-dev`). Only
# needed for `gateway.lxmf.voice` when the sender uses non-HQ PTT — HQ Opus
# works with `requirements/transcribe.txt` alone. Lazy-imported by
# semif_agent/voice_transport.py, so the core stays stdlib-only; a missing
# decoder is reported per-message, never a crash.
#
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the plan
# installs it best-effort), or manually:
# apt-get install -y libcodec2-dev
# .runtime/venv/bin/pip install -r requirements/codec2.txt
pycodec2==4.1.1
+5 -1
View File
@@ -7,7 +7,11 @@
# Voice (voice.txt) and browser (packs/browser/requirements.txt) stacks are
# hardware/optional. Voice is a repo file installed with
# `scripts/bootstrap.sh --voice`; the browser deps live WITH their pack and are
# installed by bootstrap when that pack is selected.
# installed by bootstrap when that pack is selected. transcribe.txt
# (faster-whisper only, for LXMF Sideband voice messages), tts.txt (piper-tts +
# PyAV, for LXMF voice replies) and codec2.txt (pycodec2, for non-HQ Codec2 PTT)
# are likewise optional and installed by bootstrap when `gateway.lxmf.voice` is
# enabled.
-r core.txt
-r engine.txt
-r transports.txt
+20
View File
@@ -0,0 +1,20 @@
# Voice-message transcription deps (optional).
#
# Only needed on a host whose LXMF gateway transcribes Sideband push-to-talk
# voice messages (`gateway.lxmf.voice.enabled`) but that does NOT run the voice
# gateway — `requirements/voice.txt` is hardware-dependent (PortAudio mic +
# speaker, wake word, TTS) and none of that is required here. faster-whisper
# decodes the Opus/OGG container itself (its bundled PyAV/ffmpeg) and
# transcribes, and is lazy-imported by semif_agent/voice_transport.py, so the
# core stays stdlib-only on every other host.
#
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the
# install plan picks it up on the next run), or manually:
# .runtime/venv/bin/pip install -r requirements/transcribe.txt
faster-whisper==1.2.1
# PyAV 19.0.0 (2026-09-29) REMOVED the `metadata_errors` argument to av.open(),
# which faster-whisper 1.2.1 (the latest release) still passes — so any voice
# message fails to decode with `TypeError: open() got an unexpected keyword
# argument 'metadata_errors'`. faster-whisper's git master handles both, but it
# is unreleased; pin PyAV below 19 until a release ships the fix.
av<19
+22
View File
@@ -0,0 +1,22 @@
# Voice-reply (text-to-speech) deps for the LXMF gateway (optional).
#
# When the LXMF gateway handles Sideband push-to-talk voice messages
# (`gateway.lxmf.voice.enabled`) and is configured to reply with voice
# (`gateway.lxmf.voice.reply_with_voice`, the default), it synthesizes the reply
# with Piper and encodes it to the Opus/OGG container Sideband's HQ push-to-talk
# uses (`LXMF.AM_OPUS_OGG`). That needs piper-tts (text-to-speech) and PyAV
# (libopus encoding) — NOT the hardware voice stack in `requirements/voice.txt`
# (no microphone, wake word, or speaker) and NOT transcription
# (`requirements/transcribe.txt`, which already pulls PyAV for decoding).
# Lazy-imported by semif_agent/voice_transport.py, so the core stays stdlib-only;
# a missing stack makes the reply fall back to text, never a crash.
#
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the
# install plan picks it up on the next run), or manually:
# .runtime/venv/bin/pip install -r requirements/tts.txt
piper-tts==1.8.0
onnxruntime==1.30.0
# PyAV 19.0.0 removed the `metadata_errors` argument that faster-whisper 1.2.1
# still passes to av.open() (see requirements/transcribe.txt); pin below 19 here
# too so the shared PyAV is the one both paths expect.
av<19
+4
View File
@@ -26,6 +26,10 @@
sounddevice==0.5.6
onnxruntime==1.30.0
faster-whisper==1.2.1
# PyAV 19.0.0 removed the `metadata_errors` argument that faster-whisper 1.2.1
# still passes to av.open(), breaking every transcription; see
# requirements/transcribe.txt for the full note.
av<19
piper-tts==1.8.0
webrtcvad-wheels==2.0.14.post1
# openwakeword runtime deps (installed here because openwakeword is --no-deps).
+82 -2
View File
@@ -306,7 +306,7 @@ fi
IFS=$'\x1f' read -r PLAN_ENGINE PLAN_AUTHORING PLAN_PACKS PLAN_GATEWAYS \
PLAN_GATEWAY_PLATFORMS PLAN_BRIDGE_PACKS PLAN_INSTALL_ENGINE PLAN_BRIDGE_SVC \
PLAN_GATEWAY_SVC PLAN_SIMPLEX_BIN PLAN_SIMPLEX_FWD PLAN_BROWSER PLAN_VOICE \
PLAN_PACK_REQS < <(
PLAN_TRANSCRIBE PLAN_LXMF_TTS PLAN_PACK_REQS < <(
python3 - "$PLAN" <<'PY'
import json, sys
p = json.load(open(sys.argv[1]))
@@ -326,6 +326,8 @@ print("\x1f".join([
flag("install_simplex_forward"),
flag("install_browser"),
flag("install_voice"),
flag("install_transcribe"),
flag("install_lxmf_tts"),
",".join(p.get("pack_requirements", [])),
]))
PY
@@ -350,7 +352,7 @@ NEED_TRANSPORTS=0
[[ ",$PLAN_GATEWAYS," == *",lxmf,"* ]] && NEED_TRANSPORTS=1
echo "== plan: engine=$PLAN_ENGINE | authoring=$PLAN_AUTHORING | packs=$PLAN_PACKS"
echo " gateways=${PLAN_GATEWAYS:-none} | install: engine=$PLAN_INSTALL_ENGINE transports=$NEED_TRANSPORTS bridge=$PLAN_BRIDGE_SVC gateway=$PLAN_GATEWAY_SVC browser=$PLAN_BROWSER voice=$PLAN_VOICE"
echo " gateways=${PLAN_GATEWAYS:-none} | install: engine=$PLAN_INSTALL_ENGINE transports=$NEED_TRANSPORTS bridge=$PLAN_BRIDGE_SVC gateway=$PLAN_GATEWAY_SVC browser=$PLAN_BROWSER voice=$PLAN_VOICE transcribe=$PLAN_TRANSCRIBE lxmf_tts=$PLAN_LXMF_TTS"
echo " pack deps=${PLAN_PACK_REQS:-none}"
# The live config may be split (config.json includes config/*.json); merge it so
@@ -640,6 +642,41 @@ if [[ "$PLAN_VOICE" = 1 ]]; then
"$PIP" install --no-deps openwakeword==0.6.0
fi
# --- stage 3b2: optional voice-message transcription ---------------------------
# The LXMF gateway can transcribe Sideband push-to-talk voice messages
# (`gateway.lxmf.voice.enabled`). That needs only faster-whisper (it decodes the
# Opus/OGG container itself), NOT the hardware voice stack above; lazy-imported,
# so a host that never enables it still runs every other front end.
if [[ "$PLAN_TRANSCRIBE" = 1 ]]; then
echo "== installing voice-message transcription dep (faster-whisper)"
"$PIP" install -r "$REPO_ROOT/requirements/transcribe.txt"
# Codec2 (Sideband's non-HQ PTT) is optional and native: `pycodec2` compiles
# against the system libcodec2. Best-effort — a host that can't build it still
# transcribes HQ (Opus) voice messages and reports Codec2 ones as unsupported.
if ! "$PYTHON" -c 'import pycodec2' 2>/dev/null; then
if ! ldconfig -p 2>/dev/null | grep -q 'libcodec2'; then
echo "== installing codec2 system library (optional)"
sudo apt-get update || true
sudo apt-get install -y libcodec2-dev \
|| echo "WARN: libcodec2-dev install failed; Codec2 voice will be unavailable" >&2
fi
echo "== installing Codec2 python bindings (optional)"
"$PIP" install -r "$REPO_ROOT/requirements/codec2.txt" \
|| echo "WARN: pycodec2 build failed; Codec2 voice will be unavailable (HQ Opus still works)" >&2
fi
fi
# --- stage 3b3: optional LXMF voice replies (Piper) -----------------------------
# When the LXMF gateway replies to a voice chat with a synthesized voice message
# (`gateway.lxmf.voice.reply_with_voice`), it needs Piper (text-to-speech) and
# PyAV (Opus/OGG encoding). Still no microphone stack — lazy-imported, so a host
# that only transcribes installs nothing extra.
if [[ "$PLAN_LXMF_TTS" = 1 ]]; then
echo "== installing voice-reply deps (piper-tts + PyAV)"
"$PIP" install -r "$REPO_ROOT/requirements/tts.txt"
fi
# --- stage 3c: pack-declared python deps ---------------------------------------
# A pack owns the python deps its skills/bridge need, shipped as
# packs/<name>/requirements.txt (standard pip format). The install plan lists the
@@ -735,6 +772,49 @@ if [[ "$PLAN_VOICE" = 1 ]]; then
|| echo "WARN: voice model download failed; re-run scripts/voice-models.py" >&2
fi
# --- stage 5c: LXMF voice-message STT model ------------------------------------
# Warm the faster-whisper model the LXMF gateway uses for Sideband voice
# messages into the HF cache (the model name comes from gateway.lxmf.voice.stt).
# Best-effort: faster-whisper would download it on first use anyway.
if [[ "$PLAN_TRANSCRIBE" = 1 ]]; then
LXMF_STT_MODEL="$(python3 - "$MERGED_CONFIG" <<'PY' 2>/dev/null || true
import json, sys
try:
cfg = json.load(open(sys.argv[1]))
except Exception:
print(""); raise SystemExit(0)
print(((cfg.get("gateway", {}) or {}).get("lxmf", {}) or {}).get("voice", {})
.get("stt", {}).get("model", "") or "")
PY
)"
echo "== warming voice-message STT model (${LXMF_STT_MODEL:-base.en})"
HF_HOME="$HF_CACHE" "$PYTHON" "$REPO_ROOT/scripts/voice-models.py" \
--config "$MERGED_CONFIG" --skip-wake --skip-tts --stt "$LXMF_STT_MODEL" \
|| echo "WARN: STT model download failed; it will download on first use" >&2
fi
# --- stage 5d: LXMF voice-reply TTS voice --------------------------------------
# Download the Piper voice the LXMF gateway uses for a voice reply
# (`gateway.lxmf.voice.tts.voice`) into .runtime/voice/tts. Best-effort: the
# gateway reports the missing model on first use.
if [[ "$PLAN_LXMF_TTS" = 1 ]]; then
LXMF_TTS_VOICE="$(python3 - "$MERGED_CONFIG" <<'PY' 2>/dev/null || true
import json, sys
try:
cfg = json.load(open(sys.argv[1]))
except Exception:
print(""); raise SystemExit(0)
print(((cfg.get("gateway", {}) or {}).get("lxmf", {}) or {}).get("voice", {})
.get("tts", {}).get("voice", "") or "")
PY
)"
echo "== downloading voice-reply TTS voice (${LXMF_TTS_VOICE:-en_US-lessac-medium})"
HF_HOME="$HF_CACHE" "$PYTHON" "$REPO_ROOT/scripts/voice-models.py" \
--config "$MERGED_CONFIG" --skip-wake --skip-stt --tts "$LXMF_TTS_VOICE" \
--tts-dir "$RUNTIME/voice/tts" \
|| echo "WARN: TTS voice download failed; re-run scripts/voice-models.py" >&2
fi
# --- stage 6: simplex-chat daemon binary (only when needed) --------------------
if [[ "$PLAN_SIMPLEX_BIN" = 1 ]]; then
SIMPLEX_BIN="$TOOLDIR/simplex-chat"
+36 -5
View File
@@ -41,6 +41,7 @@ from .console import (
)
from .decisions import DecisionRequest, Option
from .engine import DecisionEngine, EngineConfig, EngineUnavailable, SemIfEngine
from .ollama_systemone import OllamaSystemOneConfig, OllamaSystemOneEngine
from .winnow import WinnowConfig, WinnowEngine
from .llm import LLMClient, SemIfLLMClient
from .log import DecisionLog
@@ -54,6 +55,7 @@ from .trace import TraceLog
REPO_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_WINNOW_URL = "http://127.0.0.1:8091"
DEFAULT_OLLAMA_SYSTEMONE_URL = "http://127.0.0.1:11434"
_PATH_KEYS = (
"skill_packs",
@@ -221,14 +223,19 @@ def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
* ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`), built
from the per-machine `engine` knobs + the pinned refs in pins.json.
* ``"winnow"`` — a remote `/v1/systemone` typed-decision API
* ``"winnow"`` — a remote Winnow `/v1/systemone` typed-decision API
(`WinnowEngine`), configured by the nested `engine.winnow` block
(`base_url`/`model`/`api_key`/`timeout`/`retries`).
* ``"ollama"`` — ollama's native System One `/v1/systemone` route
(`OllamaSystemOneEngine`), configured by the nested `engine.ollama` block
(`base_url`/`model`/`keep_alive`/`api_key`/`timeout`/`retries`), probed
through ollama's own `/api/version` + `/api/show` endpoints.
The engine is always real: a provider that cannot be reached raises
`EngineUnavailable` at call time, which the scheduler treats as fatal. The
`winnow` model is required (no default) exactly as `llm.model`/`codegen.model`
are, so a misconfigured endpoint fails as an actionable config error.
`winnow` and `ollama` models are required (no default) exactly as
`llm.model`/`codegen.model` are, so a misconfigured endpoint fails as an
actionable config error.
"""
eng = config.get("engine", {}) or {}
provider = str(eng.get("provider", "semif") or "semif").lower()
@@ -247,6 +254,22 @@ def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
user_agent=str(win.get("user_agent") or "semif-agent"),
)
)
if provider == "ollama":
block = eng.get("ollama", {}) or {}
endpoint = _provider_endpoint(block, DEFAULT_OLLAMA_SYSTEMONE_URL)
return OllamaSystemOneEngine(
OllamaSystemOneConfig(
base_url=endpoint["base_url"],
model=_required_model(block, "engine.ollama"),
context_tokens=int(block.get("context_tokens", 16384)),
timeout=float(block.get("timeout", 120.0)),
retries=int(block.get("retries", 0)),
api_key=endpoint["api_key"],
extra_headers=endpoint["extra_headers"],
user_agent=str(block.get("user_agent") or "semif-agent"),
keep_alive=str(block.get("keep_alive") or ""),
)
)
return SemIfEngine(build_engine_config(config, pins))
@@ -838,6 +861,14 @@ def _build_gateway_adapter(platform: str, cfg: dict, trace):
# Contain Reticulum's config + identity under the checkout's .runtime/.
cfg.setdefault("config_dir", str(REPO_ROOT / ".runtime" / "lxmf" / "reticulum"))
cfg.setdefault("storage_path", str(REPO_ROOT / ".runtime" / "lxmf" / "router"))
# A voice reply's Piper voice lives with the voice gateway's, under the
# checkout's .runtime/ (bootstrap downloads it there).
voice_cfg = dict(cfg.get("voice") or {})
tts_cfg = dict(voice_cfg.get("tts") or {})
if not tts_cfg.get("voice_dir"):
tts_cfg["voice_dir"] = str(REPO_ROOT / ".runtime" / "voice" / "tts")
voice_cfg["tts"] = tts_cfg
cfg["voice"] = voice_cfg
return LxmfAdapter(cfg, trace=trace)
if platform == "voice":
from .gateway.voice import VoiceAdapter
@@ -1156,8 +1187,8 @@ def main(argv: list[str] | None = None) -> int:
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=(
"answers JSON fields (all optional; --answers FILE):\n"
" engine_provider (semif|winnow), winnow_base_url, winnow_model,\n"
" winnow_api_key\n"
" engine_provider (semif|winnow|ollama), winnow_base_url, winnow_model,\n"
" winnow_api_key, ollama_base_url, ollama_model, ollama_api_key\n"
" new_skill_creation (deny|ask|allow)\n"
" llm_provider (semif|ollama|opencode|openai), llm_base_url,\n"
" llm_model, llm_api_key\n"
+57 -2
View File
@@ -75,6 +75,15 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': '
'retries': {'default': 0, 'type': 'int'},
'user_agent': {'default': 'semif-agent', 'type': 'str'},
'extra_headers': {'default': {}, 'type': 'dict'}},
'ollama': {'base_url': {'default': 'http://127.0.0.1:11434', 'type': 'str'},
'model': {'default': '', 'type': 'str'},
'context_tokens': {'default': 16384, 'type': 'int'},
'api_key': {'default': '', 'type': 'str', 'secret': True},
'timeout': {'default': 120, 'type': 'int'},
'retries': {'default': 0, 'type': 'int'},
'keep_alive': {'default': '', 'type': 'str'},
'user_agent': {'default': 'semif-agent', 'type': 'str'},
'extra_headers': {'default': {}, 'type': 'dict'}},
'gguf': {'default': '', 'type': 'str'}},
'llm': {'provider': {'default': 'ollama', 'type': 'str'},
'base_url': {'default': 'http://localhost:11434/v1', 'type': 'str'},
@@ -166,7 +175,37 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': '
'storage_path': {'default': '', 'type': 'str'},
'home_channel': {'default': '', 'type': 'str'},
'reply_prefix': {'default': '', 'type': 'str'},
'text_batch_delay': {'default': 0.8, 'type': 'float'}},
'text_batch_delay': {'default': 0.8, 'type': 'float'},
# Reply with the skill's result line only (drop queue/
# urgency chatter and the `<skill>: ok —` wrapper).
'result_only': {'default': True, 'type': 'bool'},
# Transcribe Sideband push-to-talk voice messages
# (FIELD_AUDIO) into commands and (when reply_with_voice)
# answer a voice chat with a Piper voice reply. Needs only
# faster-whisper (requirements/transcribe.txt) plus
# piper-tts + PyAV (requirements/tts.txt) for replies,
# not the microphone stack.
'voice': {'enabled': {'default': False, 'type': 'bool'},
'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'},
'language': {'default': 'en', 'type': 'str'}},
'tts': {'voice': {'default': 'en_US-lessac-medium',
'type': 'str'},
'voice_dir': {'default': '', 'type': 'str'},
'speaker_id': {'default': 0, 'type': 'int'},
'length_scale': {'default': 1.0,
'type': 'float'},
'volume': {'default': 1.0, 'type': 'float'}}}},
'voice': {'enabled': {'default': False, 'type': 'bool'},
'chat_id': {'default': 'voice', 'type': 'str'},
'display_name': {'default': 'voice', 'type': 'str'},
@@ -174,6 +213,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'},
@@ -213,7 +259,16 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': '
'initial_silence_ms': {'default': 1500, 'type': 'int'},
'aggressiveness': {'default': 2, 'type': 'int'},
'energy_threshold': {'default': 200.0, 'type': 'float'}},
'follow_up_window_s': {'default': 0.0, 'type': 'float'}}},
'follow_up_window_s': {'default': 0.0, 'type': 'float'},
# Interrupt a spoken reply with the wake word: stop the
# playback, listen for a command, and either abort (a
# bare "stop"/"cancel") or run the new command. Disable
# for strict half-duplex (the agent never listens while
# speaking). `wait_s` bounds how long to wait for the
# interrupted playback to release the audio device.
'barge_in': {'enabled': {'default': True, 'type': 'bool'},
'wait_s': {'default': 2.0, 'type': 'float'},
'threshold': {'default': 0.0, 'type': 'float'}}}},
'dashboard': {'port': {'default': 8765, 'type': 'int'},
'host': {'default': '127.0.0.1', 'type': 'str'}},
'skill_packs': {'default': 'packs',
+7 -2
View File
@@ -9,7 +9,9 @@ installed. The shipped llama.cpp backend scores a local GGUF; it runs on CPU by
default, and `EngineConfig.gpu_layers` offloads to a GPU when llama-cpp-python
was built with a GPU backend (Vulkan/ROCm/CUDA). This engine is only usable on a
machine with SemIf and the pinned GGUF available; elsewhere calls raise
EngineUnavailable. The remote alternative lives in `semif_agent.winnow`.
EngineUnavailable. The remote alternatives live in `semif_agent.winnow` (the
Winnow reference server) and `semif_agent.ollama_systemone` (ollama's native
System One route).
"""
from __future__ import annotations
@@ -40,8 +42,11 @@ class DecisionEngine(ABC):
`llm.provider` / `codegen.provider`:
* ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`).
* ``"winnow"`` — a remote ``/v1/systemone`` typed-decision API
* ``"winnow"`` — a remote Winnow ``/v1/systemone`` typed-decision API
(`semif_agent.winnow.WinnowEngine`).
* ``"ollama"`` — ollama's native System One ``/v1/systemone`` route
(`semif_agent.ollama_systemone.OllamaSystemOneEngine`), probed through
ollama's own ``/api/version`` + ``/api/show`` endpoints.
The engine is always real: any failure to produce a decision raises
`EngineUnavailable`, which the scheduler treats as fatal. `generate` is the
+63 -5
View File
@@ -35,26 +35,84 @@ 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."""
#: short platform name used in request sources (`"simplex:<chat_id>"`)
name: str = "gateway"
#: Spoken front ends (the voice gateway) set this so the service speaks only
#: the skill's result line, not the scheduler's bookkeeping (queue/urgency
#: status) and not the `<skill>: ok —` wrapper. A per-platform config
#: `result_only` overrides it. Plain chat adapters leave it False.
#: Front ends that should send only the skill's result line set this, so the
#: service drops the scheduler's bookkeeping (queue/urgency status) and the
#: `<skill>: ok —` wrapper. The voice gateway and the LXMF gateway set it; a
#: per-platform config `result_only` overrides it either way.
result_only: bool = False
@abstractmethod
+494 -25
View File
@@ -11,6 +11,32 @@ This adapter is the policy layer over the neutral `LxmfDaemon` transport in
and hands authorized text to the scheduler. Unlike the SimpleX adapter there is
no external daemon and no event loop — Reticulum runs in-process on its own
threads, so batching uses a per-chat `threading.Timer`.
**Voice commands.** A Sideband push-to-talk message arrives as LXMF content with
an empty body and the audio in `FIELD_AUDIO` (`[audio_mode, bytes]`); the
transport surfaces it as a normalized `audio` dict. When `voice.enabled` is set,
this adapter transcribes that payload to text and dispatches the transcript as an
ordinary command — so the same allowlist, batching-free delivery, and reply path
apply. Both PTT shapes are handled: HQ Opus/OGG goes through
`WhisperTranscriber.transcribe_bytes` (faster-whisper's bundled PyAV decodes the
container), and non-HQ Codec2 is decoded to 8 kHz PCM by `voice_transport.
decode_codec2` (the optional `pycodec2` bindings), wrapped in a WAV, and
transcribed the same way. Transcription needs only `faster-whisper`
(`requirements/transcribe.txt`), never the microphone voice stack; Codec2
additionally needs `pycodec2` (`requirements/codec2.txt`). A missing transcriber,
missing Codec2 decoder, or undecodable mode is traced and reported, never
silently dropped; the audio itself is transient and never stored, exactly like
the voice gateway.
**Voice replies.** When `voice.reply_with_voice` is on (the default), a reply to
a chat that last messaged by voice is synthesized with Piper and sent back as a
Sideband HQ push-to-talk voice message (the reply text is encoded to Opus/OGG
and rides `FIELD_AUDIO`), so a voice user hears the answer. The reply *mode*
follows the chat's most recent inbound message: a text message reverts it to
text replies. It needs `piper-tts` + PyAV (`requirements/tts.txt`), never the
microphone stack; a missing synthesizer, a synthesis failure, or an encode
failure is traced and the reply falls back to text — never dropped. The reply
text is also sent as the message content, so a text-only client still sees it.
"""
from __future__ import annotations
@@ -18,16 +44,54 @@ 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,
build_transcriber,
check_codec2_requirements,
check_synthesis_requirements,
check_transcription_requirements,
decode_codec2,
pcm_to_opus_ogg,
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.
VOICE_FAILED_MESSAGE = (
"Sorry, I couldn't make out that voice message — please resend it or type "
"your command."
)
#: Sent when the codec is one we can't decode (the raw Opus `AM_OPUS_*` modes
#: and the binding-less 450 Codec2 modes; HQ Opus is the default and works).
VOICE_UNSUPPORTED_MESSAGE = (
"I can't read that voice format yet — send an HQ (Opus) voice message, or "
"type your command."
)
#: Sent for a Codec2 voice message when the optional Codec2 decoder is absent.
VOICE_CODEC2_MESSAGE = (
"I can't read that Codec2 voice message — the codec2 decoder isn't "
"installed. Send an HQ (Opus) voice message, or type your command."
)
class LxmfAdapter(GatewayAdapter):
name = "lxmf"
#: Send the skill's result line only — drop the scheduler's queue/urgency
#: bookkeeping and the `<skill>: ok —` wrapper, so a reply (text or voice) is
#: the answer, not the internals. Override with `gateway.lxmf.result_only:
#: false` for the full scheduler output.
result_only = True
def __init__(self, cfg: dict | None = None, trace=None):
def __init__(
self, cfg: dict | None = None, trace=None, transcriber=None, synthesizer=None
):
cfg = cfg or {}
self.allowed_users = [str(u) for u in cfg.get("allowed_users", []) or []]
self.allow_all_users = bool(cfg.get("allow_all_users", False))
@@ -51,15 +115,73 @@ class LxmfAdapter(GatewayAdapter):
)
self.config_dir = config_dir
self.storage_path = storage_path
#: Voice-message transcription (`gateway.lxmf.voice`). The transcriber is
#: built lazily from `voice.stt` (faster-whisper only) on the first
#: voice message; a test can inject one instead.
self.voice_cfg = cfg.get("voice", {}) or {}
self.voice_enabled = bool(self.voice_cfg.get("enabled", False))
#: Reply to a voice chat with a synthesized voice message (Piper). The
#: reply mode follows the chat's most recent inbound message.
self.reply_with_voice = bool(self.voice_cfg.get("reply_with_voice", True))
self.voice_max_chars = int(self.voice_cfg.get("max_speak_chars", 600) or 0)
self.voice_bitrate = int(
self.voice_cfg.get("reply_bitrate", OPUS_OGG_BITRATE) or OPUS_OGG_BITRATE
)
self._transcriber = transcriber
self._transcriber_unavailable = False
self._synthesizer = synthesizer
self._synthesizer_unavailable = False
#: Chats whose most recent inbound message was voice: their replies go
#: back as voice (until a text message reverts them).
self._voice_chats: set[str] = set()
self._voice_queue: "queue.Queue[tuple[dict, dict] | None]" = queue.Queue()
self._voice_thread: threading.Thread | None = None
self._voice_lock = threading.Lock()
self._outbound: "queue.Queue[OutboundMessage | None] | None" = None
self._buffers: dict[str, str] = {}
self._buffered: dict[str, InboundMessage] = {}
self._buffered: dict[str, dict] = {}
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 ----
def check_requirements(self) -> tuple[bool, str | None]:
# Only the transport is mandatory: text commands work without the
# optional transcription stack, and a voice message then traces
# `lxmf_voice_unavailable` rather than taking the whole gateway down.
return self.daemon.check_requirements()
# ---- authorization ----
@@ -82,17 +204,29 @@ class LxmfAdapter(GatewayAdapter):
outbound: "queue.Queue[OutboundMessage | None]",
) -> None:
self._on_inbound = on_inbound
self._outbound = outbound
def _pump() -> None:
# Translate the service's OutboundMessage queue onto the daemon's
# (chat_id, text) queue without letting scheduler work touch the
# Reticulum callback threads.
# (chat_id, text, audio) queue without letting scheduler work touch
# the Reticulum callback threads. Synthesis runs here (off the router
# thread), so a slow Piper render never stalls the transport.
while True:
message = outbound.get()
if message is None:
self.daemon.enqueue(None)
return
self.daemon.enqueue(message.chat_id, message.text)
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)
threading.Thread(
target=_pump, name="lxmf-outbound-pump", daemon=True
@@ -105,6 +239,7 @@ class LxmfAdapter(GatewayAdapter):
self._timers.clear()
for timer in timers:
timer.cancel()
self._voice_queue.put(None)
self.daemon.close()
# ---- inbound ----
@@ -121,23 +256,23 @@ class LxmfAdapter(GatewayAdapter):
display_name=display_name,
)
return
inbound = InboundMessage(
text=message.get("content") or "",
chat_id=source_hash,
chat_type="dm",
contact_id=source_hash,
display_name=display_name,
raw=message.get("raw") or {},
)
self._schedule_flush(inbound)
audio = message.get("audio")
if audio:
# A voice message puts the chat in voice-reply mode (when the reply
# path is on); a later text message reverts it.
if self.voice_enabled and self.reply_with_voice:
self._mark_voice_chat(source_hash)
self._handle_audio(message, audio)
return
self._unmark_voice_chat(source_hash)
self._schedule_flush(message)
def _schedule_flush(self, message: InboundMessage) -> None:
chat = message.chat_id
def _schedule_flush(self, message: dict) -> None:
chat = str(message.get("source_hash") or "")
text = message.get("content") or ""
with self._lock:
existing = self._buffers.get(chat)
self._buffers[chat] = (
f"{existing}\n{message.text}" if existing else message.text
)
self._buffers[chat] = f"{existing}\n{text}" if existing else text
self._buffered[chat] = message
timer = self._timers.get(chat)
if timer is not None:
@@ -154,12 +289,346 @@ class LxmfAdapter(GatewayAdapter):
self._timers.pop(chat, None)
if message is None or not text:
return
message.text = text
self._deliver(message, text)
def _deliver(self, message: dict, text: str) -> None:
"""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=message.contact_id,
display_name=message.display_name,
contact_id=source_hash,
display_name=display_name,
chars=len(text),
)
if self._on_inbound is not None:
self._on_inbound(message)
if self._on_inbound is None:
return
self._on_inbound(
InboundMessage(
text=text,
chat_id=source_hash,
chat_type="dm",
contact_id=source_hash,
display_name=display_name,
raw=message.get("raw") or {},
)
)
# ---- voice messages (Sideband push-to-talk) ----
def _handle_audio(self, message: dict, audio: dict) -> None:
"""Route a received voice message to transcription, or report why not.
Runs on the Reticulum callback thread, so it only enqueues: the actual
(slow) transcription happens on the worker thread, keeping the router
responsive. An ignored/undecodable payload keeps any caption text.
"""
source_hash = str(message.get("source_hash") or "")
codec = audio.get("codec_name")
content = message.get("content") or ""
if not self.voice_enabled:
self.daemon._event(
"lxmf_voice_ignored", contact_id=source_hash, codec=codec
)
if content:
self._schedule_flush(message)
return
kind = audio.get("kind")
if kind == "codec2":
# Codec2 needs the optional pycodec2 bindings; report a missing one
# up front rather than queueing a transcription that can't happen.
ok, _hint = check_codec2_requirements()
if not ok:
self.daemon._event(
"lxmf_voice_codec2_unavailable", contact_id=source_hash, codec=codec
)
if content:
self._schedule_flush(message)
else:
self._notify(message, VOICE_CODEC2_MESSAGE)
return
elif kind != "opus_ogg":
self.daemon._event(
"lxmf_voice_unsupported_codec", contact_id=source_hash, codec=codec
)
if content:
self._schedule_flush(message)
else:
self._notify(message, VOICE_UNSUPPORTED_MESSAGE)
return
self._ensure_voice_worker()
self._voice_queue.put((message, audio))
def _ensure_voice_worker(self) -> None:
with self._voice_lock:
if self._voice_thread is not None and self._voice_thread.is_alive():
return
self._voice_thread = threading.Thread(
target=self._voice_worker, name="lxmf-voice-worker", daemon=True
)
self._voice_thread.start()
def _voice_worker(self) -> None:
"""Transcribe queued voice messages off the Reticulum callback thread."""
while True:
item = self._voice_queue.get()
if item is None:
return
message, audio = item
text = self._transcribe(audio)
content = (message.get("content") or "").strip()
if not text:
if content:
self._deliver(message, content)
else:
self._notify(message, VOICE_FAILED_MESSAGE)
continue
self._deliver(message, f"{content}\n{text}" if content else text)
def _transcribe(self, audio: dict) -> str:
"""Transcribe one audio payload to text; "" (traced) on any failure."""
transcriber = self._ensure_transcriber()
if transcriber is None:
return ""
data = audio.get("data") or b""
if not data:
self.daemon._event("lxmf_voice_empty", codec=audio.get("codec_name"))
return ""
if audio.get("kind") == "codec2":
# Codec2 decodes to raw 8 kHz PCM; wrap it in a WAV so faster-whisper's
# PyAV decodes and resamples it like any other container.
pcm = decode_codec2(data, audio.get("codec2_rate") or 0)
if not pcm:
self.daemon._event(
"lxmf_voice_codec2_failed", codec=audio.get("codec_name")
)
return ""
payload = pcm_to_wav(pcm, 8000)
else:
payload = data
try:
text = transcriber.transcribe_bytes(payload)
except NotImplementedError:
self.daemon._event(
"lxmf_voice_transcribe_unsupported", codec=audio.get("codec_name")
)
return ""
except Exception as exc:
self.daemon._event(
"lxmf_voice_transcribe_failed", message=str(exc)[:300]
)
return ""
text = (text or "").strip()
if not text:
self.daemon._event(
"lxmf_voice_empty_transcript", codec=audio.get("codec_name")
)
return ""
self.daemon._event(
"lxmf_voice_transcribed", codec=audio.get("codec_name"), chars=len(text)
)
return text
def _ensure_transcriber(self):
"""Build (once) and return the transcriber, or None (traced) if absent."""
with self._voice_lock:
if self._transcriber is not None:
return self._transcriber
if self._transcriber_unavailable:
return None
ok, hint = check_transcription_requirements()
if not ok:
self._transcriber_unavailable = True
self.daemon._event("lxmf_voice_unavailable", message=hint)
return None
try:
self._transcriber = build_transcriber(self.voice_cfg)
except Exception as exc:
self._transcriber_unavailable = True
self.daemon._event("lxmf_voice_unavailable", message=str(exc)[:300])
return None
return self._transcriber
def _notify(self, message: dict, text: str) -> None:
"""Send a transport-level notice back to the sender (best-effort).
A transcription failure is reported to the user rather than silently
dropped; the audio itself is never stored or forwarded.
"""
chat = str(message.get("source_hash") or "")
outbound = self._outbound
if outbound is None or not chat:
return
outbound.put(OutboundMessage(chat_id=chat, text=text))
# ---- voice replies (Piper -> Opus/OGG) ----
def _mark_voice_chat(self, chat: str) -> None:
with self._lock:
self._voice_chats.add(chat)
def _unmark_voice_chat(self, chat: str) -> None:
with self._lock:
self._voice_chats.discard(chat)
def _voice_reply(self, message) -> bytes | None:
"""Synthesize a voice reply for a voice chat, or None to send text.
Runs on the outbound pump thread. Returns an OGG/Opus container (a
Sideband HQ push-to-talk payload) or None — for a text chat, an empty
reply, or any synthesis/encode failure (traced), in which case the
caller sends the text reply unchanged.
"""
if not self.reply_with_voice:
return None
chat = str(message.chat_id)
with self._lock:
is_voice = chat in self._voice_chats
if not is_voice:
return None
text = (message.text or "").strip()
if not text:
return None
if self.voice_max_chars and len(text) > self.voice_max_chars:
clipped = text[: self.voice_max_chars].rsplit(" ", 1)[0]
text = clipped or text[: self.voice_max_chars]
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:
self.daemon._event("lxmf_voice_synth_empty")
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
self.daemon._event(
"lxmf_voice_reply", chars=len(text), audio_bytes=len(audio)
)
return audio
def _ensure_synthesizer(self):
"""Build (once) and return the Piper synthesizer, or None (traced)."""
with self._voice_lock:
if self._synthesizer is not None:
return self._synthesizer
if self._synthesizer_unavailable:
return None
ok, hint = check_synthesis_requirements()
if not ok:
self._synthesizer_unavailable = True
self.daemon._event("lxmf_voice_tts_unavailable", message=hint)
return None
try:
self._synthesizer = build_synthesizer(self.voice_cfg)
except Exception as exc:
self._synthesizer_unavailable = True
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)
)
+189 -3
View File
@@ -23,9 +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
#: 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):
@@ -41,12 +46,35 @@ class VoiceAdapter(GatewayAdapter):
self.display_name = str(cfg.get("display_name") or self.chat_id)
#: `run()` blocks on the mic; this daemon owns capture/wake/STT/TTS.
self.daemon = VoiceDaemon(cfg, trace=trace, name=self.name)
#: Set by the daemon while a barge-in command is being captured, so the
#: transcribed utterance is classified as an interrupt.
self._barged_in = False
self.daemon.on_barge_in = self._on_barge_in
self._on_inbound = None
#: Utterances are handed to a worker thread, not run on the audio
#: thread: the scheduler is synchronous and can block on the decision
#: engine, and a slow or failing task must neither stop the mic being
#: read nor kill the front end. `None` asks the worker to stop.
self._inbound: "queue.Queue[InboundMessage | None]" = queue.Queue()
#: 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 ----
@@ -71,15 +99,27 @@ class VoiceAdapter(GatewayAdapter):
outbound: "queue.Queue[OutboundMessage | None]",
) -> None:
self._on_inbound = on_inbound
self._outbound = outbound
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)
@@ -112,6 +152,38 @@ 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
# is not a request: the daemon already cut the playback, and any
# reply still queued behind it is stale output the user stopped.
self.daemon._event("gateway_barge_in_stop", chars=len(message.text))
self._drop_pending_speech()
self.daemon.set_muted(False)
return
# A new command after a barge-in: the playback was already aborted,
# so just run it (and unmute once it has been handled).
self.daemon._event("gateway_barge_in_command", chars=len(message.text))
try:
if self._on_inbound is not None:
self._on_inbound(message)
except Exception as exc:
self.daemon._event("gateway_handler_failed", message=str(exc)[:300])
self.daemon.speak("Sorry, something went wrong handling that.")
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:
@@ -120,10 +192,124 @@ 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.
The daemon aborted the in-flight playback; anything waiting on the
outbound queue is output the user asked to stop, so it is dropped rather
than spoken next.
"""
outbound = self._outbound
if outbound is None:
return
dropped = 0
while True:
try:
message = outbound.get_nowait()
except queue.Empty:
break
if message is None:
outbound.put(None) # preserve the pump's shutdown sentinel
break
dropped += 1
if dropped:
self.daemon._event("gateway_speech_dropped", count=dropped)
def _on_barge_in(self, active: bool) -> None:
"""Daemon callback: mark a barge-in session (True) and its end (False)."""
self._barged_in = bool(active)
def _on_utterance(self, text: str) -> None:
text = (text or "").strip()
if not text:
return
barge_in = self._barged_in
self._barged_in = False
self.daemon._event(
"gateway_message",
contact_id=self.chat_id,
@@ -137,6 +323,6 @@ class VoiceAdapter(GatewayAdapter):
chat_type="dm",
contact_id=self.chat_id,
display_name=self.display_name,
raw={},
raw={"barge_in": True} if barge_in else {},
)
)
+225 -15
View File
@@ -31,6 +31,96 @@ MessageHandler = Callable[[InboundDict], None]
#: Zero-argument callback invoked once the router is ready to receive.
ConnectedHandler = Callable[[], None]
#: The LXMF `FIELD_AUDIO` (0x07) field a Sideband push-to-talk voice message
#: rides in. `LXMF` is optional and lazy-imported, so its stable, committed wire
#: constants are mirrored here (the same way `simplex_ws` mirrors the v7 shapes).
FIELD_AUDIO = 0x07
#: Audio modes — the first element of a `FIELD_AUDIO` value (mirrors
#: `LXMF.AM_*`). `AM_OPUS_OGG` is a complete OGG/Opus container a decoder (PyAV,
#: which `faster-whisper` bundles) reads directly; the Codec2 modes are raw
#: frames decoded by `pycodec2`.
AM_OPUS_OGG = 0x10
AUDIO_MODE_NAMES = {
0x01: "codec2_450pwb", 0x02: "codec2_450", 0x03: "codec2_700c",
0x04: "codec2_1200", 0x05: "codec2_1300", 0x06: "codec2_1400",
0x07: "codec2_1600", 0x08: "codec2_2400", 0x09: "codec2_3200",
0x10: "opus_ogg", 0x11: "opus_lbw", 0x12: "opus_mbw", 0x13: "opus_ptt",
0x14: "opus_rt_hdx", 0x15: "opus_rt_fdx", 0x16: "opus_standard",
0x17: "opus_hq", 0x18: "opus_broadcast", 0x19: "opus_lossless",
}
#: Codec2 audio modes -> the codec2 bitrate (bits/s) they decode at. `pycodec2`
#: has bindings for these; 450PWB/450 (0x01/0x02) have none, so they stay
#: undecodable. (Mirrors Sideband's `audioproc.codec2_modes`.)
CODEC2_MODE_RATES = {
0x03: 700, 0x04: 1200, 0x05: 1300, 0x06: 1400,
0x07: 1600, 0x08: 2400, 0x09: 3200,
}
#: How often the announce loop wakes to re-check the clock and interfaces.
ANNOUNCE_TICK = 1.0
#: How often to scan Reticulum interfaces for online/offline transitions.
PEER_SCAN_INTERVAL = 10.0
def audio_mode_name(codec: int) -> str:
"""A human-readable name for an audio mode id (e.g. `AM_OPUS_OGG` ->
`opus_ogg`); an unknown id is rendered as hex."""
return AUDIO_MODE_NAMES.get(codec, f"0x{codec:02x}")
def audio_decode_kind(codec: int) -> str:
"""The decode path for an audio mode.
`"opus_ogg"` (a self-contained OGG/Opus container), `"codec2"` (raw Codec2
frames), or `"unknown"` (no decode path — e.g. the raw Opus `AM_OPUS_*`
modes and the binding-less 450 Codec2 modes).
"""
if codec == AM_OPUS_OGG:
return "opus_ogg"
if codec in CODEC2_MODE_RATES:
return "codec2"
return "unknown"
def parse_audio_field(value: Any) -> dict[str, Any] | None:
"""Normalize an LXMF `FIELD_AUDIO` value into a plain dict.
The wire value is `[audio_mode, data]` (see `LXMF.FIELD_AUDIO`): an integer
codec id and the raw audio bytes. Returns
`{"codec", "codec_name", "data", "kind", "codec2_rate"}` or None when
malformed. `kind` is the decode path (`opus_ogg`/`codec2`/`unknown`);
`codec2_rate` is the bitrate for a Codec2 mode, else None.
"""
if not isinstance(value, (list, tuple)) or len(value) < 2:
return None
data = value[1]
if not isinstance(data, (bytes, bytearray)):
return None
try:
codec = int(value[0])
except (TypeError, ValueError):
return None
return {
"codec": codec,
"codec_name": audio_mode_name(codec),
"data": bytes(data),
"kind": audio_decode_kind(codec),
"codec2_rate": CODEC2_MODE_RATES.get(codec),
}
def audio_fields(audio: bytes | None) -> dict[int, Any] | None:
"""The LXMF fields for an outbound voice reply, or None for a text message.
A voice reply rides `FIELD_AUDIO` as `[AM_OPUS_OGG, ogg_bytes]` — the
Sideband HQ push-to-talk shape. Pure so the wire construction is testable
without a Reticulum router.
"""
if not audio:
return None
return {FIELD_AUDIO: [AM_OPUS_OGG, bytes(audio)]}
def _as_text(value: Any) -> str:
"""Best-effort UTF-8 text for a `str`/`bytes`/`None` LXMF field."""
@@ -87,12 +177,24 @@ def normalize_message(message: Any) -> InboundDict:
if source is not None:
display_name = _as_text(getattr(source, "display_name", None))
fields = getattr(message, "fields", None)
if not isinstance(fields, dict):
fields = {}
# A Sideband push-to-talk voice message carries its Opus/Codec2 payload in
# `FIELD_AUDIO` and an empty content; surface it as a normalized `audio` dict
# so a front end can transcribe it without knowing the wire shape.
audio = None
if FIELD_AUDIO in fields:
audio = parse_audio_field(fields.get(FIELD_AUDIO))
return {
"source_hash": source_hash,
"display_name": display_name or None,
"title": title,
"content": content,
"timestamp": getattr(message, "timestamp", None),
"fields": fields,
"audio": audio,
"raw": message,
}
@@ -101,7 +203,10 @@ class LxmfDaemon:
"""One in-process Reticulum instance + LXMF router.
`run(on_message)` blocks, announcing the delivery destination periodically
and delivering each received message to `on_message`. `enqueue(chat_id,
— and whenever a Reticulum interface or AutoInterface peer comes online, so
a peer that was not yet reachable at startup (or that joined mid-interval)
learns the destination promptly instead of waiting out `announce_interval`.
Each received message is delivered to `on_message`. `enqueue(chat_id,
text)` queues an outbound send (a `None` chat_id is the stop sentinel),
drained by an internal pump thread. `address` is the bot's LXMF address.
@@ -138,9 +243,20 @@ class LxmfDaemon:
self._reticulum = None
self._destination = None
self._address = ""
self._outbound: "queue.Queue[tuple[str, str] | None]" = queue.Queue()
#: Outbound items are `(chat_id, text, audio)`; `audio` is an OGG/Opus
#: container for a Sideband HQ push-to-talk voice reply, else None.
self._outbound: "queue.Queue[tuple[str, str, bytes | None] | None]" = (
queue.Queue()
)
self._stop = threading.Event()
self._on_message: MessageHandler | None = None
#: Last announce time, and whether an interface transition asked for
#: an immediate re-announce (set by the announce loop's interface scan).
self._last_announce = 0.0
self._announce_due = False
#: `str(interface) -> online`, so the scan can spot interfaces and
#: AutoInterface peers that just came up.
self._interface_states: dict[str, bool] = {}
# ---- requirements ----
@@ -216,6 +332,15 @@ class LxmfDaemon:
)
except Exception as exc:
self._event("lxmf_propagation_error", message=str(exc)[:300])
# Snapshot the interfaces Reticulum brought up so the announce loop can
# tell which ones (and which AutoInterface peers) come online later.
try:
self._interface_states = {
str(interface): bool(getattr(interface, "online", False))
for interface in RNS.Transport.interfaces
}
except Exception as exc:
self._event("lxmf_error", phase="interface_snapshot", message=str(exc)[:300])
self._event("lxmf_ready", address=self._address)
return self._router
@@ -225,7 +350,7 @@ class LxmfDaemon:
threading.Thread(
target=self._pump, name="lxmf-outbound-pump", daemon=True
).start()
self._announce()
self._announce("startup")
if self.on_connected is not None:
try:
self.on_connected()
@@ -234,15 +359,75 @@ class LxmfDaemon:
"lxmf_error", phase="on_connected", message=str(exc)[:300]
)
while not self._stop.wait(self._announce_wait()):
self._announce()
self._announce_loop()
def enqueue(self, chat_id: str | None, text: str = "") -> None:
"""Queue an outbound send. `chat_id=None` is the stop sentinel."""
def _announce_loop(self) -> None:
"""Announce on the interval, and whenever an interface/peer comes up.
The startup announce fires before AutoInterface has finished its
peering handshake, so it reaches no peer; a peer discovered later (or a
link that recovers) would otherwise have to wait out the whole
`announce_interval`. Re-announcing on every online transition makes a
newly-reachable peer learn the destination promptly.
"""
last_scan = 0.0
while not self._stop.is_set():
try:
now = time.time()
if self._announce_due:
self._announce_due = False
self._announce("peer discovered")
elif now - self._last_announce >= self._announce_wait():
self._announce("interval")
if now - last_scan >= PEER_SCAN_INTERVAL:
last_scan = now
if self._scan_interfaces():
self._announce_due = True
except Exception as exc:
self._event(
"lxmf_error", phase="announce_loop", message=str(exc)[:300]
)
self._stop.wait(ANNOUNCE_TICK)
def _scan_interfaces(self) -> bool:
"""Note interface transitions; True when one newly came online.
AutoInterface reports `online` only after its peering wait, and every
discovered peer is a fresh `AutoInterfacePeer` interface, so an online
transition is exactly "we may now be reachable by someone new".
"""
changed = False
try:
import RNS
for interface in RNS.Transport.interfaces:
key = str(interface)
online = bool(getattr(interface, "online", False))
prev = self._interface_states.get(key)
self._interface_states[key] = online
if online and prev is not True:
self._event("lxmf_interface_online", interface=key)
changed = True
except Exception as exc:
self._event(
"lxmf_error", phase="interface_scan", message=str(exc)[:300]
)
return changed
def enqueue(
self, chat_id: str | None, text: str = "", audio: bytes | None = None
) -> None:
"""Queue an outbound send. `chat_id=None` is the stop sentinel.
`audio` is an OGG/Opus container: it rides the LXMF `FIELD_AUDIO` field
(a Sideband HQ push-to-talk voice reply) with `text` as the message
content, so a text-only client still sees the reply.
"""
if chat_id is None:
self._outbound.put(None)
else:
self._outbound.put((str(chat_id), text))
self._outbound.put((str(chat_id), text, audio))
def close(self) -> None:
self._stop.set()
@@ -254,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):
@@ -277,12 +471,13 @@ class LxmfDaemon:
return 3600.0
return self.announce_interval
def _announce(self) -> None:
def _announce(self, reason: str = "") -> None:
if self._router is None or self._destination is None:
return
try:
self._router.announce(self._destination.hash)
self._event("lxmf_announced", address=self._address)
self._last_announce = time.time()
self._event("lxmf_announced", address=self._address, reason=reason or None)
except Exception as exc:
self._event("lxmf_error", phase="announce", message=str(exc)[:300])
@@ -309,17 +504,27 @@ class LxmfDaemon:
item = self._outbound.get()
if item is None:
return
chat_id, text = item
chat_id, text, audio = item
try:
self.send(chat_id, text)
self.send(chat_id, text, audio=audio)
except Exception as exc:
self._event(
"lxmf_send_failed", contact=chat_id, message=str(exc)[:300]
)
def send(self, destination_hex: str, text: str, timeout: float = 15.0) -> None:
def send(
self,
destination_hex: str,
text: str,
audio: bytes | None = None,
timeout: float = 15.0,
) -> None:
"""Send `text` to an LXMF address (destination hash hex).
When `audio` (an OGG/Opus container) is given it is attached in the
LXMF `FIELD_AUDIO` field as a Sideband HQ push-to-talk voice message
(`[AM_OPUS_OGG, audio]`), with `text` as the message content.
Recalls the peer identity from the network; when the path is not yet
known it requests it and waits briefly. Raises (never silently drops)
when the destination cannot be resolved — a reply must be real.
@@ -351,9 +556,14 @@ class LxmfDaemon:
if self.desired_method == "opportunistic"
else LXMF.LXMessage.DIRECT
)
message = LXMF.LXMessage(dest, self._destination, text, desired_method=method)
fields = audio_fields(audio)
message = LXMF.LXMessage(
dest, self._destination, text, desired_method=method, fields=fields
)
self._router.handle_outbound(message)
self._event("lxmf_sent", contact=destination_hex, chars=len(text))
self._event(
"lxmf_sent", contact=destination_hex, chars=len(text), audio=bool(audio)
)
# ---- tracing ----
+348
View File
@@ -0,0 +1,348 @@
"""Ollama System One decision engine: ollama's native ``/v1/systemone`` API.
An alternative to the local SemIf llama.cpp engine (`engine.SemIfEngine`) and
to the Winnow server (`semif_agent.winnow.WinnowEngine`), selected per machine
with ``engine.provider == "ollama"`` in config.json — the same provider pattern
as ``llm`` / ``codegen``.
The agent's flat decision contract (state + question + typed options) maps onto
Ollama's System One ``choice`` question: the options become the question's
``criteria`` (id -> description, or ``null`` for a bare label) and the question
becomes its ``instructions``; the server returns a probability over exactly
those keys. This provider implements the **Ollama** shape of that API (the one
documented at docs.ollama.com/api/systemone), which differs from the Winnow
reference server in ways that matter at the edges:
* no ``/health`` route — reachability/warmth is probed through Ollama's native
``GET /api/version`` and ``POST /api/show`` (which also verifies the model
exists and advertises the ``decision`` capability);
* the decision context window is read from the model's ``num_ctx`` parameter
(``/api/show``) when ``engine.ollama.context_tokens`` is 0, so generated
skill bodies are sized to what the server really loaded;
* ``keep_alive`` is an Ollama request knob, not part of the System One contract;
* choice criteria descriptions are the Ollama subset ``string | null`` (never
an object) and at least two options are required;
* decision models do not generate text, so ``generate`` is unavailable here
(use ``llm.provider == "ollama"`` for the chat path).
The engine is real: any network, HTTP, or distribution failure raises
`EngineUnavailable`, which the scheduler treats as fatal — there is no fallback
model and no fabricated reply.
"""
from __future__ import annotations
import json
import math
import re
import threading
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from .decisions import DecisionRequest, DecisionResult
from .engine import DecisionEngine, EngineUnavailable
@dataclass
class OllamaSystemOneConfig:
"""Per-machine settings for the Ollama System One engine (`engine.ollama`)."""
#: The Ollama server root — **no** ``/v1`` suffix (System One lives at
#: ``/v1/systemone`` on the root server, unlike the OpenAI-compatible API).
base_url: str = "http://127.0.0.1:11434"
model: str = ""
#: The model's decision context window, in tokens. 0 asks the server (the
#: model's `num_ctx` parameter, then its architecture context length), so
#: the fidelity-state budget mirrors the window the server really loaded.
context_tokens: int = 16384
timeout: float = 120.0
#: Transient-failure retries before declaring the engine unavailable. 0
#: means a single attempt: an unreachable remote engine is fatal by
#: contract.
retries: int = 0
#: Bearer key for Ollama's cloud models (``https://ollama.com``); empty for
#: a local server.
api_key: str = ""
extra_headers: dict | None = None
user_agent: str = "semif-agent"
#: Ollama's model-unload policy for the request (a duration such as "5m",
#: or seconds). Empty keeps the server's own keep-alive setting.
keep_alive: str = ""
def _context_from_show(show: dict) -> int | None:
"""The model's context window from an Ollama ``/api/show`` payload.
Ollama reports ``parameters`` either as modelfile text
(``"num_ctx 16384\\n..."``) or as a mapping, depending on version; the
architecture context length in ``model_info`` is the fallback. Returns
``None`` when neither shape carries a usable number.
"""
params = show.get("parameters")
if isinstance(params, str):
match = re.search(r"(?m)^\s*num_ctx\s+(\d+)\s*$", params)
if match:
return int(match.group(1))
elif isinstance(params, dict):
value = params.get("num_ctx")
if value is not None:
try:
return int(value)
except (TypeError, ValueError):
pass
info = show.get("model_info")
if isinstance(info, dict):
# Prefer the text model's context length over a vision tower's.
candidates = [
value
for key, value in info.items()
if str(key).endswith(".context_length") and "vision" not in str(key)
]
for value in candidates:
try:
return int(value)
except (TypeError, ValueError):
continue
return None
class OllamaSystemOneEngine(DecisionEngine):
"""One Ollama System One endpoint, used for every decision.
Scoring maps a `DecisionRequest` -> a single ``choice`` question and reads
the returned distribution back over the requested option ids. The endpoint
is a single-slot server, so calls serialize on an internal lock exactly as
`SemIfEngine` serializes on its llama.cpp context.
"""
label = "ollama"
def __init__(self, config: OllamaSystemOneConfig):
self.config = config
self._lock = threading.Lock()
self._loaded = False
self._discovered_context: int | None = None
@property
def context_tokens(self) -> int:
configured = int(self.config.context_tokens or 0)
if configured > 0:
return configured
return int(self._discovered_context or 16384)
@property
def loaded(self) -> bool:
return self._loaded
# ---- transport ----
def _headers(self) -> dict:
headers = {
"content-type": "application/json",
"accept": "application/json",
}
if self.config.user_agent:
headers["user-agent"] = self.config.user_agent
if self.config.api_key:
headers["authorization"] = f"Bearer {self.config.api_key}"
for key, value in (self.config.extra_headers or {}).items():
headers[str(key)] = str(value)
return headers
def _request(self, path: str, payload: dict | None = None) -> dict:
"""GET (no payload) or POST JSON, or raise `EngineUnavailable`."""
url = self.config.base_url.rstrip("/") + path
data = None
if payload is not None:
data = json.dumps(payload).encode("utf-8")
attempts = max(0, int(self.config.retries)) + 1
last: Exception | None = None
for attempt in range(attempts):
request = urllib.request.Request(
url,
data=data,
method="POST" if data is not None else "GET",
headers=self._headers(),
)
try:
with urllib.request.urlopen(
request, timeout=self.config.timeout
) as response:
body = response.read().decode("utf-8", errors="replace")
parsed = json.loads(body)
if not isinstance(parsed, dict):
raise EngineUnavailable(
f"Ollama response from {url} is not a JSON object"
)
return parsed
except urllib.error.HTTPError as exc:
detail = ""
try:
# Ollama reports failures as {"error": "..."}.
detail = exc.read().decode("utf-8", errors="replace")[:300]
except Exception:
pass
last = EngineUnavailable(
f"HTTP {exc.code} from {url}: {detail}".strip()
)
# A 4xx (except 429) will not succeed on retry.
if 400 <= exc.code < 500 and exc.code != 429:
break
except EngineUnavailable:
raise
except Exception as exc: # URLError, timeout, socket, JSONDecodeError
last = exc
if attempt + 1 < attempts:
time.sleep(min(2.0**attempt, 5.0))
if isinstance(last, EngineUnavailable):
raise last
raise EngineUnavailable(
f"Ollama request to {url} failed: {type(last).__name__}: {last}"
)
def _post(self, path: str, payload: dict) -> dict:
return self._request(path, payload)
# ---- DecisionEngine ----
def warm(self) -> None:
"""Verify the server and the configured model, then mark loaded.
Ollama has no ``/health`` route: ``GET /api/version`` proves the server
answers and ``POST /api/show`` proves the model is pulled (404 when it
is not) and lets a 0 ``context_tokens`` follow the model's real
``num_ctx``. A model that advertises capabilities without ``decision``
is rejected with an actionable error instead of failing on first use.
"""
self._request("/api/version")
show = self._post("/api/show", {"model": self.config.model})
if int(self.config.context_tokens or 0) <= 0:
discovered = _context_from_show(show)
if discovered:
self._discovered_context = discovered
capabilities = show.get("capabilities")
if isinstance(capabilities, list) and capabilities:
if "decision" not in capabilities:
raise EngineUnavailable(
f"Ollama model {self.config.model!r} does not advertise the "
"'decision' capability (capabilities: "
f"{', '.join(str(c) for c in capabilities)}); point "
"engine.ollama.model at a System One model"
)
self._loaded = True
def call(self, request: DecisionRequest) -> DecisionResult:
option_ids = [option.id for option in request.options]
if len(option_ids) < 2:
raise EngineUnavailable(
"Ollama System One choice questions need at least two options"
)
state = request.state if isinstance(request.state, str) else json.dumps(
request.state
)
if not state.strip():
raise EngineUnavailable("Ollama System One requires a non-empty state")
# Ollama's choice criteria descriptions are `string | null`; a bare
# label is the explicit `null` form.
criteria = {
option.id: (option.description.strip() or None)
for option in request.options
}
payload = {
"model": self.config.model,
"state": state,
"questions": {
"decision": {
"type": "choice",
"instructions": request.question,
"criteria": criteria,
}
},
}
keep_alive = str(self.config.keep_alive or "").strip()
if keep_alive:
payload["keep_alive"] = keep_alive
with self._lock:
started = time.perf_counter()
body = self._post("/v1/systemone", payload)
elapsed = time.perf_counter() - started
answers = body.get("answers")
answer = answers.get("decision") if isinstance(answers, dict) else None
if not isinstance(answer, dict):
raise EngineUnavailable(
"Ollama response is missing answers.decision"
)
if answer.get("type") not in (None, "choice"):
raise EngineUnavailable(
f"Ollama answer type {answer.get('type')!r} is not 'choice'"
)
raw = answer.get("probabilities")
if not isinstance(raw, dict):
raise EngineUnavailable("Ollama answer is missing probabilities")
if set(raw) != set(option_ids):
raise EngineUnavailable(
"Ollama probabilities do not match the requested options: "
f"{sorted(raw)} != {sorted(option_ids)}"
)
choice = answer.get("choice")
if choice is not None and choice not in option_ids:
raise EngineUnavailable(
f"Ollama choice {choice!r} is not one of the requested options"
)
try:
values = [float(raw[option_id]) for option_id in option_ids]
except (TypeError, ValueError) as exc:
raise EngineUnavailable(
f"Ollama probabilities are not numeric: {exc}"
) from exc
if any(
(not math.isfinite(value)) or value < 0.0 or value > 1.0
for value in values
):
raise EngineUnavailable(
"Ollama returned a non-finite or out-of-range probability"
)
total = sum(values)
if total <= 0.0:
raise EngineUnavailable("Ollama returned an all-zero distribution")
probabilities = [value / total for value in values]
usage = body.get("usage") if isinstance(body.get("usage"), dict) else {}
self._loaded = True
return DecisionResult(
request=request,
option_ids=option_ids,
probabilities=probabilities,
extra={
"input_tokens": usage.get("input_tokens"),
"output_tokens": usage.get("output_tokens"),
"forward_seconds": elapsed,
"total_seconds": elapsed,
"raw_probability_sum": total,
"served_model": body.get("model"),
"choice": choice,
"confidence": answer.get("confidence"),
},
)
def generate(
self,
messages: list[dict],
temperature: float = 0.0,
max_tokens: int = 256,
) -> str:
"""Unavailable: System One decision models do not generate text.
Use ``llm.provider == "ollama"`` (an OpenAI-compatible chat endpoint) for
text; pointing ``llm.provider`` at this decision engine would ask a
classifier to write prose, so it is refused rather than faked.
"""
raise EngineUnavailable(
"the ollama System One decision engine does not generate text; "
"configure llm.provider = \"ollama\" for the chat path"
)
+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)
+23 -1
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,
@@ -54,6 +55,7 @@ from .skills import (
CreateSkill,
DeletedSkills,
Skill,
SkillCatalog,
SkillDraft,
SkillStore,
apply_tombstones,
@@ -435,8 +437,21 @@ 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.
self.catalog = SkillCatalog(self._tree_snapshot)
self.ctx = ActionContext(
engine=self.engine, config=config, timers=self.timers, admin=self
engine=self.engine,
config=config,
timers=self.timers,
speech=self.speech,
admin=self,
catalog=self.catalog,
)
self.runner = SkillRunner(
self.ctx,
@@ -1055,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,
+113 -5
View File
@@ -46,7 +46,7 @@ from .packs import SkillPack, pack_enabled
#: ``llm``/``codegen`` providers the wizard can emit.
PROVIDERS = ("semif", "ollama", "opencode", "openai")
#: ``engine`` providers.
ENGINE_PROVIDERS = ("semif", "winnow")
ENGINE_PROVIDERS = ("semif", "winnow", "ollama")
#: New-skill creation modes.
AUTHORING_MODES = ("deny", "ask", "allow")
@@ -71,10 +71,14 @@ class Answers:
"""The wizard's answers, and the source of truth for the generated config."""
# Decision engine.
engine_provider: str = "semif" # semif | winnow
engine_provider: str = "semif" # semif | winnow | ollama
winnow_base_url: str = ""
winnow_model: str = ""
winnow_api_key: str = ""
#: Ollama's native System One route (`engine.ollama`).
ollama_base_url: str = ""
ollama_model: str = ""
ollama_api_key: str = ""
# New-skill authoring: deny | ask | allow.
new_skill_creation: str = "deny"
@@ -99,6 +103,13 @@ class Answers:
# Gateway platforms to enable.
gateways: list[str] = field(default_factory=list)
# LXMF gateway: transcribe Sideband push-to-talk voice messages into
# commands (install `requirements/transcribe.txt`; faster-whisper only) and
# reply to a voice chat with a Piper voice message (install
# `requirements/tts.txt`; piper-tts + PyAV).
lxmf_voice: bool = False
lxmf_voice_reply: bool = True
# IANA timezone; empty uses the host zone.
timezone: str = ""
@@ -344,7 +355,7 @@ def run_interview(
output(
" The decision engine routes every request. It runs locally on the\n"
" pinned SemIf 4B GGUF by default (no network), or against a remote\n"
" Winnow /v1/systemone server."
" Winnow /v1/systemone server or an Ollama System One decision model."
)
answers.engine_provider = _ask_choice(
input_fn,
@@ -353,6 +364,7 @@ def run_interview(
[
("semif", "local SemIf 4B (llama.cpp, pinned GGUF)"),
("winnow", "remote Winnow decision server"),
("ollama", "remote Ollama System One model (/v1/systemone)"),
],
1,
)
@@ -369,6 +381,25 @@ def run_interview(
answers.winnow_api_key = _ask_text(
input_fn, output, " winnow API key (blank for none)", "", secret=True
)
elif answers.engine_provider == "ollama":
answers.ollama_base_url = _ask_text(
input_fn, output, " ollama base URL", "http://127.0.0.1:11434"
)
model = ""
while not model:
model = _ask_text(
input_fn, output, " ollama System One model (required)"
)
if not model:
output(" engine.ollama.model is required.")
answers.ollama_model = model
answers.ollama_api_key = _ask_text(
input_fn,
output,
" ollama API key (blank for a local server)",
"",
secret=True,
)
# 2. Skill authoring.
output("")
@@ -392,7 +423,15 @@ def run_interview(
answers.new_skill_creation = mode
if mode != "deny":
output("")
_collect_llm(input_fn, output, answers, label="llm", allow_semif=True)
# The Ollama System One decision model does not generate text, so it
# cannot back the small `llm` task; only a real endpoint can.
_collect_llm(
input_fn,
output,
answers,
label="llm",
allow_semif=answers.engine_provider != "ollama",
)
output("")
_collect_llm(input_fn, output, answers, label="codegen", allow_semif=False)
@@ -462,6 +501,29 @@ def run_interview(
default=answers.gateways,
)
# 5b. LXMF voice messages (Sideband push-to-talk).
if "lxmf" in answers.gateways:
output("")
output("LXMF voice messages")
output(
" Sideband can send push-to-talk voice messages. The agent can\n"
" transcribe them into commands, and reply to a voice chat with a\n"
" synthesized voice message (Piper)."
)
mode = _ask_choice(
input_fn,
output,
"lxmf voice",
[
("off", "ignore voice messages"),
("transcribe", "transcribe to commands, reply with text"),
("reply", "transcribe, and reply with a synthesized voice"),
],
3,
)
answers.lxmf_voice = mode in ("transcribe", "reply")
answers.lxmf_voice_reply = mode == "reply"
# 6. Timezone.
output("")
answers.timezone = _ask_text(
@@ -499,6 +561,14 @@ def build_config(answers: Answers, packs: Sequence[SkillPack]) -> dict:
_set_secret_or_literal(
winnow, "api_key", answers.winnow_api_key, "engine_winnow_api_key"
)
elif answers.engine_provider == "ollama":
ollama = engine.setdefault("ollama", {})
if answers.ollama_base_url:
ollama["base_url"] = answers.ollama_base_url
ollama["model"] = answers.ollama_model
_set_secret_or_literal(
ollama, "api_key", answers.ollama_api_key, "engine_ollama_api_key"
)
# Authoring mode.
config["new_skill_creation"] = answers.new_skill_creation
@@ -568,6 +638,12 @@ def build_config(answers: Answers, packs: Sequence[SkillPack]) -> dict:
for platform in ("simplex", "lxmf", "voice"):
gateway.setdefault(platform, {})["enabled"] = platform in answers.gateways
gateway.setdefault("humanize", {})["enabled"] = bool(answers.gateways)
# Sideband voice messages are transcribed only when the LXMF gateway is on
# and the answer opted in; needs faster-whisper (requirements/transcribe.txt).
# A voice reply adds Piper + PyAV (requirements/tts.txt).
voice_block = gateway.setdefault("lxmf", {}).setdefault("voice", {})
voice_block["enabled"] = bool("lxmf" in answers.gateways and answers.lxmf_voice)
voice_block["reply_with_voice"] = bool(answers.lxmf_voice_reply)
return config
@@ -577,6 +653,8 @@ def build_secrets(answers: Answers) -> dict:
secrets: dict[str, str] = {}
if answers.engine_provider == "winnow" and answers.winnow_api_key:
secrets["engine_winnow_api_key"] = answers.winnow_api_key
if answers.engine_provider == "ollama" and answers.ollama_api_key:
secrets["engine_ollama_api_key"] = answers.ollama_api_key
if answers.llm_provider != "semif" and answers.llm_api_key:
secrets["llm_api_key"] = answers.llm_api_key
if answers.codegen_api_key:
@@ -632,6 +710,17 @@ def build_plan(answers: Answers, packs: Sequence[SkillPack]) -> dict:
"install_simplex_forward": "simplex" in answers.packs,
"install_browser": "browser" in answers.packs,
"install_voice": "voice" in answers.gateways,
# faster-whisper only (no microphone stack): transcribe Sideband voice
# messages when the LXMF gateway is on and the answer opted in.
"install_transcribe": "lxmf" in answers.gateways and bool(answers.lxmf_voice),
# Piper + PyAV (no microphone stack): reply to a voice chat with a
# synthesized voice message when the LXMF gateway handles voice and the
# answer wants voice replies.
"install_lxmf_tts": (
"lxmf" in answers.gateways
and bool(answers.lxmf_voice)
and bool(answers.lxmf_voice_reply)
),
}
@@ -665,6 +754,21 @@ def plan_from_config(config: dict, packs: Sequence[SkillPack]) -> dict:
"install_simplex_forward": "simplex" in enabled,
"install_browser": "browser" in enabled,
"install_voice": "voice" in gateways,
"install_transcribe": bool(
(((config.get("gateway", {}) or {}).get("lxmf", {}) or {})
.get("voice", {}) or {})
.get("enabled")
),
"install_lxmf_tts": bool(
(((config.get("gateway", {}) or {}).get("lxmf", {}) or {})
.get("voice", {}) or {})
.get("enabled")
)
and bool(
(((config.get("gateway", {}) or {}).get("lxmf", {}) or {})
.get("voice", {}) or {})
.get("reply_with_voice", True)
),
}
@@ -772,7 +876,11 @@ def _print_summary(answers: Answers, output: Callable[[str], None]) -> None:
+ (
"local SemIf 4B"
if answers.engine_provider == "semif"
else f"remote Winnow ({answers.winnow_model or '?'})"
else (
f"remote Winnow ({answers.winnow_model or '?'})"
if answers.engine_provider == "winnow"
else f"remote Ollama System One ({answers.ollama_model or '?'})"
)
)
)
output(f" authoring: {answers.new_skill_creation}")
+9 -1
View File
@@ -34,6 +34,7 @@ from .log import DecisionLog
from .skills import (
CANNED_CATEGORIES,
DETERMINISTIC_CATEGORIES,
HOUSEKEEPING_CATEGORY,
ActionContext,
Skill,
SkillStore,
@@ -147,7 +148,14 @@ class SkillRunner:
engine=self.ctx.engine,
config=merged,
timers=self.ctx.timers,
admin=self.ctx.admin,
# 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`.
admin=self.ctx.admin if skill.category == HOUSEKEEPING_CATEGORY else None,
catalog=self.ctx.catalog,
)
def _unresolved(self, skill: Skill, request: Request) -> list[str]:
+34 -1
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,10 +46,42 @@ 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.
# must never reach into the agent (the read-only `catalog` is their view).
admin: object | None = None
# A read-only view of the agent's own skill catalog (categories -> skills),
# for an introspection skill that reports what the agent can do. Unlike
# `admin` it exposes no mutation, so an ordinary body may read it.
catalog: "SkillCatalog | None" = None
@dataclass
class SkillCatalog:
"""Read-only introspection of the agent's own skill tree.
An ordinary skill body must never reach into the agent (`ctx.admin` is for
the built-in housekeeping meta skills), but a skill that reports the agent's
own capabilities legitimately needs to see the tree. This is that surface:
reads only — the category list and the skills inside one category — with no
way to mutate. `provider` returns the live tree (the scheduler supplies a
locked snapshot), so a skill authored after startup is still listed.
"""
provider: Callable[[], dict[str, list[Skill]]]
def categories(self) -> dict[str, str]:
"""Category id -> scope description, for every category in the tree."""
return category_descriptions(self.provider())
def skills(self, category: str) -> list[str]:
"""The leaf names inside one category (empty when it is unknown)."""
return sorted(skill.name for skill in self.provider().get(category, []))
def _noop_act(ctx: ActionContext, request: Request) -> ActionResult:
+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
+487 -61
View File
@@ -15,8 +15,14 @@ Audio contract: 16 kHz, mono, signed 16-bit little-endian PCM, read in fixed
resampling is done in the loop.
Design notes:
- **Half-duplex.** Capture frames are discarded while a reply is being spoken,
so the agent never transcribes its own voice (no barge-in yet).
- **Half-duplex by default, barge-in optional.** Capture frames are normally
discarded while a reply is being spoken, so the agent never transcribes its
own voice. With barge-in enabled (`barge_in.enabled`), the wake word is still
scored during playback: the user can interrupt a spoken reply, the playback
is aborted, and the following command is captured and handed to the front end
(which decides whether it is a stop or a new request). Speech is muted while
the interrupt command is captured and handled, so the interrupted reply does
not resume over the user.
- The engine interfaces are plain classes so tests can inject fakes and drive
the loop without hardware or the optional packages.
"""
@@ -48,6 +54,28 @@ _REQUIRED_MODULES: tuple[tuple[str, str], ...] = (
("onnxruntime", "onnxruntime"),
)
#: The one package a transcribe-only front end needs (see
#: `check_transcription_requirements`). `faster-whisper` bundles PyAV, whose
#: ffmpeg decodes an incoming Opus/OGG voice message to PCM.
_TRANSCRIBE_MODULES: tuple[tuple[str, str], ...] = (
("faster_whisper", "faster-whisper"),
)
#: The packages a voice-reply front end needs (see
#: `check_synthesis_requirements`): Piper for text-to-speech and PyAV for the
#: Opus/OGG container a Sideband HQ push-to-talk reply rides in. No microphone,
#: wake word, or transcription is implied — a headless host can synthesize a
#: reply without the hardware voice stack.
_SYNTHESIS_MODULES: tuple[tuple[str, str], ...] = (
("piper", "piper-tts"),
("av", "av (PyAV, Opus/OGG encoding)"),
)
#: Sideband's HQ push-to-talk container (`LXMF.AM_OPUS_OGG`) is 48 kHz mono
#: OGG/Opus; a reply's PCM is resampled to that rate before encoding.
OPUS_OGG_SAMPLE_RATE = 48000
OPUS_OGG_BITRATE = 24000
# --------------------------------------------------------------------------- #
# Engine interfaces (fakes are injected in tests)
@@ -83,6 +111,15 @@ class Transcriber:
def transcribe(self, pcm16: bytes) -> str:
raise NotImplementedError
def transcribe_bytes(self, data: bytes) -> str:
"""Transcribe an encoded audio container (e.g. OGG/Opus) to text.
Default: not supported. `WhisperTranscriber` overrides it so a received
voice message (a Sideband PTT Opus/OGG payload) is transcribed without a
separate decode step.
"""
raise NotImplementedError
def close(self) -> None:
pass
@@ -119,6 +156,17 @@ class AudioIO:
def write(self, pcm16: bytes, sample_rate: int) -> None:
raise NotImplementedError
def play(self, pcm16: bytes, sample_rate: int, stop_event=None) -> bool:
"""Play PCM, returning `False` if aborted early via `stop_event`.
The default plays the whole buffer in one `write`. The real device
overrides this to stream in small chunks so a barge-in stops the reply
promptly instead of after the whole buffer; a fake that only implements
`write` still plays through here.
"""
self.write(pcm16, sample_rate)
return True
def flush(self) -> None:
"""Drop any buffered capture frames (called after speaking to clear echo)."""
@@ -236,6 +284,10 @@ class WhisperTranscriber(Transcriber):
self._model = WhisperModel(str(model or "base.en"), device=str(device or "cpu"),
compute_type=str(compute_type or "int8"))
@staticmethod
def _join(segments) -> str:
return " ".join(segment.text.strip() for segment in segments).strip()
def transcribe(self, pcm16: bytes) -> str:
import numpy as np
@@ -246,7 +298,25 @@ class WhisperTranscriber(Transcriber):
beam_size=self.beam_size,
vad_filter=self.vad_filter,
)
return " ".join(segment.text.strip() for segment in segments).strip()
return self._join(segments)
def transcribe_bytes(self, data: bytes) -> str:
"""Transcribe an encoded audio container (e.g. OGG/Opus).
faster-whisper decodes the container to 16 kHz mono internally via PyAV
(its own bundled ffmpeg), so a PTT voice message's Opus/OGG payload is
transcribed directly — no separate decode step and no system ffmpeg.
`data` is the raw container bytes.
"""
import io
segments, _info = self._model.transcribe(
io.BytesIO(bytes(data)),
language=self.language,
beam_size=self.beam_size,
vad_filter=self.vad_filter,
)
return self._join(segments)
class PiperSynthesizer(Synthesizer):
@@ -509,6 +579,40 @@ class SoundDeviceAudio(AudioIO):
) as stream:
stream.write(pcm16)
def play(self, pcm16: bytes, sample_rate: int, stop_event=None) -> bool:
"""Stream PCM in small chunks so a barge-in can abort playback.
A single `write` of the whole buffer blocks until the device drains it,
so an interrupt could only take effect after the reply had finished. The
buffer is played in ~50 ms chunks instead, checking `stop_event` between
them; on a stop the stream is aborted (discarding what is still buffered)
and `False` is returned. One output stream is opened for the whole
buffer, so the chunks play gaplessly.
"""
import sounddevice as sd
rate = self.output_sample_rate or self._device_rate(
self.output_device, "output"
)
if rate != int(sample_rate):
pcm16 = _resample_pcm16(pcm16, int(sample_rate), rate)
chunk = max(BYTES_PER_SAMPLE, int(rate * 0.05) * BYTES_PER_SAMPLE) # 50 ms
with sd.RawOutputStream(
samplerate=rate,
channels=1,
dtype="int16",
device=self.output_device,
) as stream:
for offset in range(0, len(pcm16), chunk):
if stop_event is not None and stop_event.is_set():
try:
stream.abort()
except Exception:
pass
return False
stream.write(pcm16[offset : offset + chunk])
return True
def flush(self) -> None:
try:
while not self._frames.empty():
@@ -572,10 +676,228 @@ def _build_vad(cfg: dict) -> VadGate:
return EnergyVadGate(threshold=float(vad_cfg.get("energy_threshold", 200.0)))
def build_transcriber(cfg: dict) -> Transcriber:
"""Build just the speech-to-text engine from an `stt` config block.
`build_engines` also needs a microphone, a wake word, and TTS; a headless
front end that only transcribes received audio — the LXMF gateway handling a
Sideband PTT voice message — uses this instead, so it needs only
`faster-whisper` and none of the hardware voice stack.
"""
stt_cfg = (cfg or {}).get("stt", {}) or {}
return WhisperTranscriber(
model=str(stt_cfg.get("model", "base.en") or "base.en"),
device=str(stt_cfg.get("device", "cpu") or "cpu"),
compute_type=str(stt_cfg.get("compute_type", "int8") or "int8"),
language=str(stt_cfg.get("language", "en") or "en"),
)
def check_transcription_requirements() -> tuple[bool, str | None]:
"""Return `(ok, install_hint)` for the transcribe-only path.
Unlike `VoiceDaemon.check_requirements` this needs no microphone, wake word,
or TTS — only `faster-whisper` — so a headless host can transcribe incoming
voice messages without the hardware voice stack. Never raises.
"""
missing = []
for module, hint in _TRANSCRIBE_MODULES:
try:
importlib.import_module(module)
except Exception:
missing.append(hint)
if missing:
return False, (
"install the transcription stack (requirements/transcribe.txt): "
+ "; ".join(missing)
)
return True, None
def check_synthesis_requirements() -> tuple[bool, str | None]:
"""Return `(ok, install_hint)` for the voice-reply (Piper) path.
A voice reply needs Piper (text-to-speech) and PyAV (to encode the
synthesized PCM into the Opus/OGG container a Sideband HQ push-to-talk
message rides in). Neither a microphone, a wake word, nor transcription is
implied — the headless counterpart of `VoiceDaemon.check_requirements`.
Never raises.
"""
missing = []
for module, hint in _SYNTHESIS_MODULES:
try:
importlib.import_module(module)
except Exception:
missing.append(hint)
if missing:
return False, (
"install the voice-reply stack (requirements/tts.txt): "
+ "; ".join(missing)
)
return True, None
def pcm_to_opus_ogg(
pcm16: bytes, sample_rate: int, bitrate: int = OPUS_OGG_BITRATE
) -> bytes:
"""Encode 16-bit mono PCM into an OGG/Opus container (Sideband HQ PTT).
A received voice message is Opus/OGG (`LXMF.AM_OPUS_OGG`), so a voice reply
is encoded to the same container: the PCM is resampled to 48 kHz (Opus's
fullband rate) with PyAV's `AudioResampler` and muxed into OGG by its
bundled libopus. Returns `b""` on any failure (the caller falls back to a
text reply) — never raises, so a missing PyAV degrades gracefully.
"""
if not pcm16 or len(pcm16) < BYTES_PER_SAMPLE:
return b""
try:
import av
except Exception:
return b""
try:
rate = int(sample_rate or OPUS_OGG_SAMPLE_RATE)
source = av.AudioFrame(
format="s16", layout="mono", samples=len(pcm16) // BYTES_PER_SAMPLE
)
source.sample_rate = rate
source.planes[0].update(pcm16)
if rate == OPUS_OGG_SAMPLE_RATE:
frames = [source]
else:
resampler = av.AudioResampler(
format="s16", layout="mono", rate=OPUS_OGG_SAMPLE_RATE
)
# PyAV's `resample` returns a list of frames (older versions a single
# frame or None); normalize both shapes.
frames = resampler.resample(source)
if not isinstance(frames, list):
frames = [frames]
tail = resampler.resample(None)
frames += tail if isinstance(tail, list) else [tail]
frames = [frame for frame in frames if frame is not None]
if not frames:
return b""
buffer = io.BytesIO()
container = av.open(buffer, mode="w", format="ogg")
stream = container.add_stream("libopus", rate=OPUS_OGG_SAMPLE_RATE)
stream.layout = "mono"
stream.bit_rate = int(bitrate or OPUS_OGG_BITRATE)
try: # voice-optimised mode (Sideband's HQ PTT uses the voice profile)
stream.codec_context.options = {"application": "voip"}
except Exception:
pass
for frame in frames:
for packet in stream.encode(frame):
container.mux(packet)
for packet in stream.encode(None):
container.mux(packet)
container.close()
return buffer.getvalue()
except Exception:
return b""
def check_codec2_requirements() -> tuple[bool, str | None]:
"""Return `(ok, install_hint)` for Codec2 voice-message decoding.
Codec2 (Sideband's non-HQ push-to-talk) needs the optional `pycodec2`
bindings, which compile against the system `libcodec2`. Never raises.
"""
try:
importlib.import_module("pycodec2")
except Exception:
return False, (
"pip install pycodec2 (needs the system libcodec2: "
"apt install libcodec2-dev)"
)
return True, None
def decode_codec2(data: bytes, rate: int) -> bytes | None:
"""Decode a raw Codec2 bitstream to 8 kHz mono int16 PCM.
`rate` is the codec2 bitrate in bits/s (700..3200). Returns None when the
optional `pycodec2` bindings (or the mode) are unavailable, so the caller
reports the message unsupported rather than guessing. Frames shorter than a
full codec frame are dropped; decoding mirrors Sideband's per-frame loop.
"""
if not data or not rate:
return None
try:
import pycodec2
except Exception:
return None
try:
codec = pycodec2.Codec2(int(rate))
bytes_per_frame = int(codec.bytes_per_frame())
except Exception:
return None
if bytes_per_frame <= 0:
return None
try:
import numpy as np
except Exception:
return None
frames = [
np.asarray(codec.decode(data[offset : offset + bytes_per_frame]), dtype=np.int16)
for offset in range(0, len(data) - bytes_per_frame + 1, bytes_per_frame)
]
if not frames:
return None
return np.concatenate(frames).astype(np.int16).tobytes()
def pcm_to_wav(pcm16: bytes, sample_rate: int, channels: int = 1) -> bytes:
"""Wrap raw int16 PCM in a minimal in-memory WAV container (stdlib).
Lets a non-container payload (Codec2 frames decoded to 8 kHz PCM) ride the
same transcription path as an Opus/OGG message: faster-whisper's PyAV decodes
the WAV and resamples it to 16 kHz, so the boundary needs no manual resample.
"""
import io
import wave
buffer = io.BytesIO()
with wave.open(buffer, "wb") as wav:
wav.setnchannels(int(channels))
wav.setsampwidth(2)
wav.setframerate(int(sample_rate))
wav.writeframes(pcm16)
return buffer.getvalue()
def _build_piper(tts_cfg: dict) -> PiperSynthesizer:
"""Build the Piper synthesizer from a `tts` config block (shared by the
microphone front end and the headless LXMF voice-reply path)."""
tts_voice = resolve_model_path(
str(tts_cfg.get("voice", "") or ""),
str(tts_cfg.get("voice_dir", "") or ""),
(".onnx",),
)
return PiperSynthesizer(
tts_voice,
speaker_id=int(tts_cfg.get("speaker_id", 0) or 0),
length_scale=float(tts_cfg.get("length_scale", 1.0) or 1.0),
volume=float(tts_cfg.get("volume", 1.0) or 1.0),
)
def build_synthesizer(cfg: dict) -> Synthesizer:
"""Build just the text-to-speech engine from a `tts` config block.
`build_engines` also needs a microphone, a wake word, and speech-to-text; a
headless front end that only synthesizes a reply — the LXMF gateway
answering a Sideband push-to-talk voice message with a Piper voice message —
uses this instead, so it needs only `piper-tts` (and PyAV to encode the
reply), none of the hardware voice stack.
"""
tts_cfg = (cfg or {}).get("tts", {}) or {}
return _build_piper(tts_cfg)
def build_engines(cfg: dict, trace=None) -> VoiceEngines:
"""Construct the real engine bundle from a `gateway.voice` config block."""
wake_cfg = cfg.get("wake", {}) or {}
stt_cfg = cfg.get("stt", {}) or {}
tts_cfg = cfg.get("tts", {}) or {}
audio_cfg = cfg.get("audio", {}) or {}
@@ -584,11 +906,6 @@ def build_engines(cfg: dict, trace=None) -> VoiceEngines:
str(wake_cfg.get("model_dir", "") or ""),
(".onnx", ".tflite"),
)
tts_voice = resolve_model_path(
str(tts_cfg.get("voice", "") or ""),
str(tts_cfg.get("voice_dir", "") or ""),
(".onnx",),
)
return VoiceEngines(
wake=OpenWakeWordDetector(
wake_model,
@@ -596,18 +913,8 @@ def build_engines(cfg: dict, trace=None) -> VoiceEngines:
inference_framework=str(wake_cfg.get("inference_framework", "onnx")),
),
vad=_build_vad(cfg),
stt=WhisperTranscriber(
model=str(stt_cfg.get("model", "base.en") or "base.en"),
device=str(stt_cfg.get("device", "cpu") or "cpu"),
compute_type=str(stt_cfg.get("compute_type", "int8") or "int8"),
language=str(stt_cfg.get("language", "en") or "en"),
),
tts=PiperSynthesizer(
tts_voice,
speaker_id=int(tts_cfg.get("speaker_id", 0) or 0),
length_scale=float(tts_cfg.get("length_scale", 1.0) or 1.0),
volume=float(tts_cfg.get("volume", 1.0) or 1.0),
),
stt=build_transcriber(cfg),
tts=_build_piper(tts_cfg),
audio=SoundDeviceAudio(
input_device=str(audio_cfg.get("input_device", "") or ""),
output_device=str(audio_cfg.get("output_device", "") or ""),
@@ -633,7 +940,7 @@ class VoiceDaemon:
"""
def __init__(self, cfg: dict | None = None, trace=None, engines: VoiceEngines | None = None,
name: str = "voice", input_ready=None):
name: str = "voice", input_ready=None, on_barge_in=None):
cfg = cfg or {}
self.config = cfg
self.trace = trace
@@ -643,6 +950,11 @@ class VoiceDaemon:
#: is still running the current request), so a second command cannot be
#: started before the first reaches a result. None = always ready.
self.input_ready = input_ready
#: Optional callback the loop invokes around a barge-in: `True` when the
#: wake word is heard over a spoken reply (playback aborted, listening
#: begins), `False` once that listening session ends. The front end uses
#: it to classify the following utterance as an interrupt.
self.on_barge_in = on_barge_in
self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.2))
#: After the wake word, how long to wait for the command's speech to
#: begin before giving up (a natural pause after "hey <word>" — e.g.
@@ -688,12 +1000,29 @@ class VoiceDaemon:
self.cue_submit_notes = _parse_notes(cue.get("submit_notes"))
self.cue_note_gap_ms = int(cue.get("note_gap_ms", 20) or 0)
#: Barge-in: keep scoring the wake word while a reply is playing, abort
#: the playback on a wake, and mute speech while the interrupt command
#: is captured/handled. `wait_s` bounds how long to wait for the
#: interrupted playback to release the audio device. `threshold`
#: overrides the wake threshold for barge-in only (a higher bar keeps
#: the agent's own TTS from self-triggering; 0 = use `wake.threshold`).
barge_cfg = cfg.get("barge_in", {}) or {}
self.barge_in_enabled = bool(barge_cfg.get("enabled", True))
self.barge_in_wait_s = float(barge_cfg.get("wait_s", 2.0) or 0.0)
self.barge_in_threshold = (
float(barge_cfg.get("threshold", 0.0) or 0.0) or self.wake_threshold
)
self._engines = engines
self._engines_lock = threading.Lock()
self._audio_lock = threading.Lock() # serialize cue/speak playback
self._on_utterance: UtteranceHandler | None = None
self._stop = threading.Event()
self._speaking = threading.Event()
#: Set while a reply is being played; `_interrupt` aborts that playback.
self._interrupt = threading.Event()
#: While set, `speak` drops text (a barge-in is being captured/handled).
self._mute = threading.Event()
# ---- requirements ----
@@ -766,49 +1095,111 @@ class VoiceDaemon:
return
if not pcm:
continue
barge_in = False
if self._speaking.is_set():
continue
score = engines.wake.score(pcm)
if score < self.wake_threshold:
continue
if self.input_ready is not None and not self.input_ready():
# The single scheduler slot is still running the current
# request: hold the wake word until it reaches a result (or
# pauses for the user's answer), so a new command cannot start
# while one is in flight. Reset the detector so the same wake
# phrase does not immediately re-fire once the slot frees.
# Half-duplex by default: the agent's own voice is discarded.
# With barge-in enabled the wake word is still scored, so the
# user can interrupt a spoken reply ("hey <word>, stop").
if not self.barge_in_enabled:
continue
score = engines.wake.score(pcm)
if score < self.barge_in_threshold:
continue
barge_in = True
self._begin_barge_in(engines, score)
else:
score = engines.wake.score(pcm)
if score < self.wake_threshold:
continue
delivered = False
try:
if self.input_ready is not None and not self.input_ready():
# The single scheduler slot is still running the current
# request: hold the wake word until it reaches a result (or
# pauses for the user's answer), so a new command cannot
# start while one is in flight. Reset the detector so the
# same wake phrase does not immediately re-fire once the
# slot frees.
try:
engines.wake.reset()
except Exception:
pass
self._event("voice_wake_blocked", score=round(float(score), 3))
continue
if not barge_in:
self._event("voice_wake", score=round(float(score), 3))
try:
engines.wake.reset()
except Exception:
pass
self._event("voice_wake_blocked", score=round(float(score), 3))
continue
self._event("voice_wake", score=round(float(score), 3))
self._cue(self.cue_frequency, self.cue_duration_ms)
# Wait for the command to start rather than assuming it is glued
# to the wake word (the wake frame + a natural pause are
# discarded so the command is not truncated).
wait_for_speech_ms = self.listen_timeout_ms
utterance = self._collect(engines, pcm, wait_for_speech_ms=wait_for_speech_ms)
if not utterance:
continue
try:
text = engines.stt.transcribe(utterance)
except Exception as exc:
self._event("voice_stt_failed", message=str(exc)[:300])
continue
text = (text or "").strip()
if not text:
self._event("voice_stt_empty", samples=len(utterance) // BYTES_PER_SAMPLE)
continue
self._event("voice_transcribed", chars=len(text))
self._bling()
delivered = True
if self._on_utterance is not None:
self._on_utterance(text)
finally:
if barge_in:
self._end_barge_in(delivered)
def _begin_barge_in(self, engines: VoiceEngines, score: float) -> None:
"""Abort the current reply and start listening for an interrupt.
The playback is stopped (the daemon's `play` watches `_interrupt`) and
speech is muted so the interrupted reply cannot resume over the user
while the interrupt command is captured and handled. The front end is
told via `on_barge_in(True)` so it can classify the next utterance.
"""
self._event("voice_barge_in", score=round(float(score), 3))
self._mute.set()
self._interrupt.set()
if self.on_barge_in is not None:
try:
engines.wake.reset()
self.on_barge_in(True)
except Exception:
pass
self._cue(self.cue_frequency, self.cue_duration_ms)
# Wait for the command to start rather than assuming it is glued to
# the wake word (the wake frame + a natural pause are discarded so
# the command is not truncated).
wait_for_speech_ms = self.listen_timeout_ms
utterance = self._collect(engines, pcm, wait_for_speech_ms=wait_for_speech_ms)
if not utterance:
continue
# Wait for the interrupted playback to release the audio device so the
# wake cue and the captured command are not played over it.
deadline = time.time() + self.barge_in_wait_s
while self._speaking.is_set() and time.time() < deadline:
time.sleep(0.005)
try:
engines.audio.flush() # drop the reply's echo captured while speaking
except Exception:
pass
def _end_barge_in(self, delivered: bool) -> None:
"""Close a barge-in session.
`delivered` is True when a command was transcribed and handed to the
front end; the front end then owns un-muting (it un-mutes only after the
interrupt has been handled, so the interrupted reply never resumes). A
barge-in that captured nothing un-mutes here.
"""
self._interrupt.clear()
if self.on_barge_in is not None:
try:
text = engines.stt.transcribe(utterance)
except Exception as exc:
self._event("voice_stt_failed", message=str(exc)[:300])
continue
text = (text or "").strip()
if not text:
self._event("voice_stt_empty", samples=len(utterance) // BYTES_PER_SAMPLE)
continue
self._event("voice_transcribed", chars=len(text))
self._bling()
if self._on_utterance is not None:
self._on_utterance(text)
self.on_barge_in(False)
except Exception:
pass
if not delivered or self.on_barge_in is None:
self._mute.clear()
def _collect(self, engines: VoiceEngines, first_frame: bytes, wait_for_speech_ms: int = 0) -> bytes:
"""Accumulate frames from the wake word until trailing silence.
@@ -987,15 +1378,42 @@ class VoiceDaemon:
except Exception as exc:
self._event("voice_cue_failed", message=str(exc)[:200])
def set_muted(self, muted: bool) -> None:
"""Mute/unmute spoken replies (used around a barge-in)."""
if muted:
self._mute.set()
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()
if not text:
return
if self._mute.is_set():
# A barge-in is in progress: the user interrupted and is giving a
# new command, so a pending reply is dropped rather than played over
# them. Replies after the interrupt is handled are spoken normally.
self._event("voice_speak_suppressed", chars=len(text))
return
if self.max_speak_chars and len(text) > self.max_speak_chars:
clipped = text[: self.max_speak_chars].rsplit(" ", 1)[0]
text = (clipped or text[: self.max_speak_chars]) + "…"
engines = self._ensure_engines()
# Start from a clean wake-detector state so the reply's own audio does
# not inherit a stale partial match.
try:
engines.wake.reset()
except Exception:
pass
self._speaking.set()
self._event("voice_speak_start", chars=len(text))
try:
@@ -1010,11 +1428,19 @@ class VoiceDaemon:
else 0.0,
)
if pcm:
with self._audio_lock:
engines.audio.open_output(sample_rate)
# The instant the first reply audio is handed to the device.
self._event("voice_playback_start", ts=time.time(), chars=len(text))
engines.audio.write(pcm, sample_rate)
if self._interrupt.is_set():
# A barge-in landed during synthesis; skip playback.
self._event("voice_speak_aborted", chars=len(text))
else:
with self._audio_lock:
engines.audio.open_output(sample_rate)
# The instant the first reply audio is handed to the device.
self._event("voice_playback_start", ts=time.time(), chars=len(text))
completed = engines.audio.play(
pcm, sample_rate, stop_event=self._interrupt
)
if not completed:
self._event("voice_speak_interrupted", chars=len(text))
self._event("voice_spoke", chars=len(text))
except Exception as exc:
self._event("voice_speak_failed", message=str(exc)[:300])
+7 -5
View File
@@ -8,10 +8,12 @@ question type: the options become the question's ``criteria`` (id -> description
and the question becomes its ``instructions``; the server returns a probability
over exactly those keys.
Winnow runs as its own process (``winnow-server``); see ``local/ENVIRONMENT.md``
for this deployment. The engine is real: any network, HTTP, or distribution
failure raises `EngineUnavailable`, which the scheduler treats as fatal — there
is no fallback model and no fabricated reply.
It works against any server implementing that route: the reference
``winnow-server``, or an OpenAI-compatible host (ollama 0.40+) serving a
``decision`` model such as ``clef-flash``. See ``local/ENVIRONMENT.md`` for this
deployment. The engine is real: any network, HTTP, or distribution failure
raises `EngineUnavailable`, which the scheduler treats as fatal — there is no
fallback model and no fabricated reply.
"""
from __future__ import annotations
@@ -24,7 +26,7 @@ import urllib.error
import urllib.request
from dataclasses import dataclass
from .decisions import DecisionRequest, DecisionResult
from .decisions import DecisionRequest, DecisionResult, Option
from .engine import DecisionEngine, EngineUnavailable
+30
View File
@@ -19,6 +19,7 @@ from semif_agent.engine import (
_install_gpu_state_reset,
_offloading_params,
)
from semif_agent.ollama_systemone import OllamaSystemOneEngine
from semif_agent.winnow import WinnowEngine
PINS = {
@@ -111,3 +112,32 @@ def test_build_engine_selects_the_winnow_provider():
def test_build_engine_winnow_requires_a_model():
with pytest.raises(SystemExit):
build_engine({"engine": {"provider": "winnow", "winnow": {}}}, PINS)
def test_build_engine_selects_the_ollama_systemone_provider():
engine = build_engine(
{
"engine": {
"provider": "ollama",
"ollama": {
"base_url": "http://example:11434",
"model": "clef-flash",
"context_tokens": 8192,
"keep_alive": "5m",
},
}
},
PINS,
)
assert isinstance(engine, OllamaSystemOneEngine)
assert isinstance(engine, DecisionEngine)
assert engine.label == "ollama"
assert engine.config.base_url == "http://example:11434"
assert engine.config.model == "clef-flash"
assert engine.context_tokens == 8192
assert engine.config.keep_alive == "5m"
def test_build_engine_ollama_requires_a_model():
with pytest.raises(SystemExit):
build_engine({"engine": {"provider": "ollama", "ollama": {}}}, PINS)
+617
View File
@@ -10,6 +10,7 @@ live-daemon integration concern, not a unit test.
import asyncio
import json
import queue
import time
from semif_agent.cli import _gateway_address_callback
@@ -549,6 +550,574 @@ def test_lxmf_denies_unknown_sender_without_dispatch():
assert seen == []
def test_lxmf_adapter_is_result_only():
from semif_agent.gateway.lxmf import LxmfAdapter
# The LXMF gateway replies with the skill's result line only (drop the
# scheduler's bookkeeping and the `<skill>: ok —` wrapper), overridable via
# `gateway.lxmf.result_only: false`.
assert LxmfAdapter({}).result_only is True
def test_lxmf_service_sends_result_only(tmp_path):
from semif_agent.gateway.lxmf import LxmfAdapter
scheduler = build_scheduler(tmp_path)
service = GatewayService(scheduler, LxmfAdapter({"allow_all_users": True}))
service._reply("lxmf", "c", "time.now: ok — 12:00", kind="result")
service._reply("lxmf", "c", "queued", kind="status")
service._reply("lxmf", "c", "Which account?", kind="question")
assert drain_outbound(service) == ["12:00", "Which account?"]
def test_lxmf_config_can_turn_result_only_off(tmp_path):
from semif_agent.gateway.lxmf import LxmfAdapter
scheduler = build_scheduler(tmp_path)
service = GatewayService(
scheduler,
LxmfAdapter({"allow_all_users": True}),
config={"lxmf": {"result_only": False}},
)
service._reply("lxmf", "c", "time.now: ok — 12:00", kind="result")
service._reply("lxmf", "c", "queued", kind="status")
assert drain_outbound(service) == ["time.now: ok — 12:00", "queued"]
# ---- LXMF voice (Sideband push-to-talk) messages ----
OPUS_AUDIO = {
"codec": 0x10,
"codec_name": "opus_ogg",
"data": b"OggS-payload",
"kind": "opus_ogg",
"codec2_rate": None,
}
CODEC2_AUDIO = {
"codec": 0x08,
"codec_name": "codec2_2400",
"data": b"\x01\x02\x03\x04\x05\x06",
"kind": "codec2",
"codec2_rate": 2400,
}
class FakeTranscriber:
"""A transcriber double: records the raw payloads, returns fixed text."""
def __init__(self, text="set a timer for five minutes", error=None):
self.text = text
self.error = error
self.calls: list = []
def transcribe_bytes(self, data):
self.calls.append(data)
if self.error is not None:
raise self.error
return self.text
def _wait(predicate, timeout=2.0):
deadline = time.time() + timeout
while time.time() < deadline:
if predicate():
return True
time.sleep(0.02)
return False
def test_lxmf_transcribes_voice_message_into_a_command():
from semif_agent.gateway.lxmf import LxmfAdapter
transcriber = FakeTranscriber("what time is it")
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}}, transcriber=transcriber
)
seen: list = []
adapter._on_inbound = seen.append
adapter._on_item(
{
"source_hash": "ab" * 16,
"content": "",
"display_name": None,
"audio": dict(OPUS_AUDIO),
}
)
assert _wait(lambda: seen)
assert seen[0].text == "what time is it"
assert seen[0].chat_id == "ab" * 16
assert transcriber.calls == [b"OggS-payload"]
def test_lxmf_voice_disabled_ignores_audio():
from semif_agent.gateway.lxmf import LxmfAdapter
# A transcriber is present, but `voice.enabled` is not — nothing runs.
adapter = LxmfAdapter({"allow_all_users": True}, transcriber=FakeTranscriber("hi"))
seen: list = []
adapter._on_inbound = seen.append
adapter._on_item(
{"source_hash": "ab" * 16, "content": "", "audio": dict(OPUS_AUDIO)}
)
time.sleep(0.1)
assert seen == []
def test_lxmf_voice_unsupported_codec_notifies_instead_of_dropping():
from semif_agent.gateway.lxmf import LxmfAdapter, VOICE_UNSUPPORTED_MESSAGE
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
transcriber=FakeTranscriber(),
)
adapter._outbound = queue.Queue()
adapter._on_item(
{
"source_hash": "ab" * 16,
"content": "",
"audio": {"codec": 0x01, "codec_name": "codec2_450pwb", "data": b"x",
"kind": "unknown", "codec2_rate": None},
}
)
message = adapter._outbound.get(timeout=2)
assert message.chat_id == "ab" * 16
assert message.text == VOICE_UNSUPPORTED_MESSAGE
def test_lxmf_transcribes_codec2_voice_message(monkeypatch):
import semif_agent.gateway.lxmf as lxmf
from semif_agent.gateway.lxmf import LxmfAdapter
monkeypatch.setattr(lxmf, "check_codec2_requirements", lambda: (True, None))
decoded = []
def fake_decode(data, rate):
decoded.append((data, rate))
return b"\x00\x00" * 320 # 20 ms at 8 kHz
monkeypatch.setattr(lxmf, "decode_codec2", fake_decode)
transcriber = FakeTranscriber("turn on the kitchen light")
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}}, transcriber=transcriber
)
seen: list = []
adapter._on_inbound = seen.append
adapter._on_item(
{"source_hash": "ab" * 16, "content": "", "audio": dict(CODEC2_AUDIO)}
)
assert _wait(lambda: seen)
assert seen[0].text == "turn on the kitchen light"
assert decoded == [(CODEC2_AUDIO["data"], 2400)]
# The Codec2 PCM is wrapped in a WAV before transcription.
assert transcriber.calls and transcriber.calls[0][:4] == b"RIFF"
def test_lxmf_codec2_unavailable_notifies(monkeypatch):
import semif_agent.gateway.lxmf as lxmf
from semif_agent.gateway.lxmf import LxmfAdapter, VOICE_CODEC2_MESSAGE
monkeypatch.setattr(lxmf, "check_codec2_requirements", lambda: (False, "no pycodec2"))
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
transcriber=FakeTranscriber(),
)
adapter._outbound = queue.Queue()
adapter._on_item(
{"source_hash": "ab" * 16, "content": "", "audio": dict(CODEC2_AUDIO)}
)
message = adapter._outbound.get(timeout=2)
assert message.text == VOICE_CODEC2_MESSAGE
def test_lxmf_transcribe_failure_notifies():
from semif_agent.gateway.lxmf import LxmfAdapter, VOICE_FAILED_MESSAGE
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
transcriber=FakeTranscriber(error=RuntimeError("boom")),
)
adapter._outbound = queue.Queue()
seen: list = []
adapter._on_inbound = seen.append
adapter._on_item(
{"source_hash": "ab" * 16, "content": "", "audio": dict(OPUS_AUDIO)}
)
message = adapter._outbound.get(timeout=2)
assert message.text == VOICE_FAILED_MESSAGE
assert seen == []
def test_lxmf_voice_keeps_caption_when_transcription_fails():
from semif_agent.gateway.lxmf import LxmfAdapter
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
transcriber=FakeTranscriber(error=RuntimeError("boom")),
)
adapter._outbound = queue.Queue()
seen: list = []
adapter._on_inbound = seen.append
adapter._on_item(
{
"source_hash": "ab" * 16,
"content": "please create a task",
"audio": dict(OPUS_AUDIO),
}
)
assert _wait(lambda: seen)
assert seen[0].text == "please create a task"
assert adapter._outbound.empty()
# ---- LXMF voice replies (Piper -> Opus/OGG) ----
class FakeSynthesizer:
"""A synthesizer double: records texts, returns fixed PCM/rate."""
def __init__(self, pcm=b"\x00\x00" * 100, sample_rate=22050, error=None):
self.pcm = pcm
self.sample_rate = sample_rate
self.error = error
self.calls: list = []
def synthesize(self, text):
self.calls.append(text)
if self.error is not None:
raise self.error
return self.pcm, self.sample_rate
def _outbound(chat, text):
from semif_agent.gateway.base import OutboundMessage
return OutboundMessage(chat_id=chat, text=text)
def test_lxmf_voice_message_marks_chat_and_replies_with_voice(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"OggS")
synth = FakeSynthesizer()
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
transcriber=FakeTranscriber("what time is it"),
synthesizer=synth,
)
# A voice message marks the chat for voice replies.
adapter._on_item(
{"source_hash": "ab" * 16, "content": "", "audio": dict(OPUS_AUDIO)}
)
assert "ab" * 16 in adapter._voice_chats
audio = adapter._voice_reply(_outbound("ab" * 16, "It is 12:00."))
assert audio == b"OggS"
assert synth.calls == ["It is 12:00."]
def test_lxmf_text_chat_replies_with_text():
from semif_agent.gateway.lxmf import LxmfAdapter
synth = FakeSynthesizer()
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
transcriber=FakeTranscriber("hi"),
synthesizer=synth,
)
# No voice message from this chat: a text reply.
assert adapter._voice_reply(_outbound("ab" * 16, "hello")) is None
assert synth.calls == []
def test_lxmf_text_message_reverts_chat_to_text_replies():
from semif_agent.gateway.lxmf import LxmfAdapter
synth = FakeSynthesizer()
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
transcriber=FakeTranscriber("hi"),
synthesizer=synth,
)
adapter._on_item(
{"source_hash": "ab" * 16, "content": "", "audio": dict(OPUS_AUDIO)}
)
assert "ab" * 16 in adapter._voice_chats
adapter._on_item({"source_hash": "ab" * 16, "content": "now in text"})
assert "ab" * 16 not in adapter._voice_chats
def test_lxmf_reply_with_voice_disabled_sends_text():
from semif_agent.gateway.lxmf import LxmfAdapter
synth = FakeSynthesizer()
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True, "reply_with_voice": False}},
transcriber=FakeTranscriber("hi"),
synthesizer=synth,
)
adapter._on_item(
{"source_hash": "ab" * 16, "content": "", "audio": dict(OPUS_AUDIO)}
)
assert "ab" * 16 not in adapter._voice_chats
assert adapter._voice_reply(_outbound("ab" * 16, "hello")) is None
def test_lxmf_voice_reply_falls_back_to_text_on_synth_failure():
from semif_agent.gateway.lxmf import LxmfAdapter
synth = FakeSynthesizer(error=RuntimeError("piper boom"))
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
transcriber=FakeTranscriber("hi"),
synthesizer=synth,
)
adapter._on_item(
{"source_hash": "ab" * 16, "content": "", "audio": dict(OPUS_AUDIO)}
)
assert adapter._voice_reply(_outbound("ab" * 16, "hello")) is None
def test_lxmf_voice_reply_bounds_length(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"OggS")
synth = FakeSynthesizer()
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True, "max_speak_chars": 10}},
transcriber=FakeTranscriber("hi"),
synthesizer=synth,
)
adapter._on_item(
{"source_hash": "ab" * 16, "content": "", "audio": dict(OPUS_AUDIO)}
)
adapter._voice_reply(_outbound("ab" * 16, "one two three four five six"))
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:
@@ -583,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()
)
+138 -1
View File
@@ -7,7 +7,14 @@ a live-integration concern.
"""
from semif_agent.gateway.lxmf import LxmfAdapter
from semif_agent.lxmf_transport import LxmfDaemon, normalize_message
from semif_agent.lxmf_transport import (
AM_OPUS_OGG,
FIELD_AUDIO,
LxmfDaemon,
audio_fields,
normalize_message,
parse_audio_field,
)
# ---- requirements ----
@@ -94,3 +101,133 @@ def test_normalize_message_handles_none_content():
assert normalized["source_hash"] == ""
assert normalized["content"] == ""
assert normalized["title"] == ""
# ---- voice (Sideband push-to-talk) audio field ----
def test_parse_audio_field_opus_ogg_uses_the_container_path():
audio = parse_audio_field([0x10, b"OggS-payload"])
assert audio == {
"codec": 0x10,
"codec_name": "opus_ogg",
"data": b"OggS-payload",
"kind": "opus_ogg",
"codec2_rate": None,
}
def test_parse_audio_field_codec2_maps_to_a_bitrate():
audio = parse_audio_field([0x08, b"\x00\x01"])
assert audio["codec_name"] == "codec2_2400"
assert audio["kind"] == "codec2"
assert audio["codec2_rate"] == 2400
def test_parse_audio_field_450_codec2_has_no_binding():
# 450PWB/450 have no pycodec2 bindings, so they stay undecodable.
audio = parse_audio_field([0x01, b"\x00\x01"])
assert audio["kind"] == "unknown"
assert audio["codec2_rate"] is None
def test_parse_audio_field_rejects_malformed():
assert parse_audio_field("nope") is None
assert parse_audio_field([0x10]) is None
assert parse_audio_field([0x10, "not-bytes"]) is None
assert parse_audio_field(["x", b"data"]) is None
def test_normalize_message_extracts_audio_field():
class _Msg:
source_hash = bytes.fromhex("ab" * 16)
content = b""
title = b""
fields = {0x07: [0x10, b"OggS"]}
normalized = normalize_message(_Msg())
assert normalized["audio"]["codec_name"] == "opus_ogg"
assert normalized["audio"]["data"] == b"OggS"
assert normalized["audio"]["kind"] == "opus_ogg"
assert normalized["fields"][0x07][0] == 0x10
def test_normalize_message_without_fields_has_no_audio():
class _Msg:
content = b"plain text"
normalized = normalize_message(_Msg())
assert normalized["audio"] is None
assert normalized["fields"] == {}
# ---- outbound voice replies ----
def test_audio_fields_wraps_ogg_as_sideband_hq_ptt():
fields = audio_fields(b"OggS-payload")
assert fields == {FIELD_AUDIO: [AM_OPUS_OGG, b"OggS-payload"]}
assert AM_OPUS_OGG == 0x10
def test_audio_fields_none_for_text_or_empty():
assert audio_fields(None) is None
assert audio_fields(b"") is None
def test_enqueue_carries_audio_on_the_outbound_queue():
daemon = LxmfDaemon(config_dir="x", storage_path="y")
daemon.enqueue("ab" * 16, "hello", audio=b"OggS")
assert daemon._outbound.get_nowait() == ("ab" * 16, "hello", b"OggS")
# The stop sentinel is unchanged.
daemon.enqueue(None)
assert daemon._outbound.get_nowait() is None
# ---- interface-transition re-announce ----
def test_announce_records_time_and_reason():
daemon = LxmfDaemon(config_dir="x", storage_path="y")
announced = []
class _Router:
def announce(self, destination_hash):
announced.append(destination_hash)
class _Destination:
hash = b"\x00" * 16
daemon._router = _Router()
daemon._destination = _Destination()
assert daemon._last_announce == 0.0
daemon._announce("startup")
assert announced == [b"\x00" * 16]
assert daemon._last_announce > 0.0
def test_scan_interfaces_flags_only_newly_online(monkeypatch):
import sys
import types
class _Iface:
def __init__(self, name, online):
self._name = name
self.online = online
def __str__(self):
return self._name
a = _Iface("A", False)
b = _Iface("B", True)
fake_rns = types.SimpleNamespace(
Transport=types.SimpleNamespace(interfaces=[a, b])
)
monkeypatch.setitem(sys.modules, "RNS", fake_rns)
daemon = LxmfDaemon(config_dir="x", storage_path="y")
daemon._interface_states = {"A": False, "B": True}
assert daemon._scan_interfaces() is False # steady state: nothing changed
a.online = True
assert daemon._scan_interfaces() is True # A came online
assert daemon._scan_interfaces() is False # now recorded online
fake_rns.Transport.interfaces.append(_Iface("C", True))
assert daemon._scan_interfaces() is True # a fresh peer interface
+336
View File
@@ -0,0 +1,336 @@
"""Pure-stdlib tests for the Ollama System One decision engine provider.
The engine is exercised over a real loopback HTTP server (the transport is not
mocked): the handler records requests and returns canned ollama
``/api/version``, ``/api/show``, and ``/v1/systemone`` responses, so the tests
prove the decision-contract mapping, the ollama-specific probing, and the strict
distribution validation. No model, no GGUF, no external network.
"""
from __future__ import annotations
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.engine import EngineUnavailable
from semif_agent.ollama_systemone import OllamaSystemOneConfig, OllamaSystemOneEngine
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *args): # keep the test output quiet
pass
def _read(self) -> dict:
length = int(self.headers.get("content-length", 0) or 0)
raw = self.rfile.read(length) if length else b"{}"
return json.loads(raw or b"{}")
def _send(self, status: int, payload: dict) -> None:
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
self.server.state.setdefault("gets", []).append(self.path)
if self.path == "/api/version":
self._send(
self.server.state.get("version_status", 200),
{"version": "0.40.13"},
)
else:
self._send(404, {"error": "not found"})
def do_POST(self):
body = self._read()
self.server.state.setdefault("requests", []).append(
(self.path, body, {k.lower(): v for k, v in self.headers.items()})
)
if self.path == "/api/show":
status = self.server.state.get("show_status", 200)
response = self.server.state.get("show_response")
if response is None:
response = _default_show()
self._send(status, response)
elif self.path == "/v1/systemone":
status = self.server.state.get("systemone_status", 200)
response = self.server.state.get("systemone_response")
if response is None:
response = _default_systemone(body)
self._send(status, response)
else:
self._send(404, {"error": "not found"})
def _default_show() -> dict:
return {
"model": "clef-flash",
"parameters": "num_ctx 16384",
"capabilities": ["decision"],
"model_info": {"clef.context_length": 262144},
}
def _default_systemone(body: dict) -> dict:
criteria = body["questions"]["decision"]["criteria"]
keys = list(criteria)
probs = {
key: (0.9 if index == 0 else 0.1 / max(len(keys) - 1, 1))
for index, key in enumerate(keys)
}
# Return the keys in REVERSE order to prove the engine aligns by id, not by
# position in the returned object.
return {
"model": "clef-flash",
"answers": {
"decision": {
"type": "choice",
"choice": keys[0],
"probabilities": dict(reversed(list(probs.items()))),
"confidence": 0.8,
}
},
"usage": {"input_tokens": 42, "output_tokens": 1},
}
@pytest.fixture()
def ollama():
server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
server.state = {}
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base = f"http://127.0.0.1:{server.server_address[1]}"
yield server, base
server.shutdown()
server.server_close()
def _engine(base: str, **cfg) -> OllamaSystemOneEngine:
return OllamaSystemOneEngine(
OllamaSystemOneConfig(base_url=base, model="clef-flash", timeout=5.0, **cfg)
)
def _decision(*option_ids: str) -> DecisionRequest:
return DecisionRequest(
state="the user said hello",
question="Which category handles this request?",
options=[Option(oid, f"description for {oid}") for oid in option_ids],
)
def test_call_maps_decision_to_a_choice_question(ollama):
server, base = ollama
result = _engine(base).call(_decision("response", "calendar"))
assert result.option_ids == ["response", "calendar"]
assert result.prob("response") == pytest.approx(0.9)
assert result.prob("calendar") == pytest.approx(0.1)
assert result.selected == "response"
assert result.extra["input_tokens"] == 42
assert result.extra["choice"] == "response"
assert result.extra["confidence"] == 0.8
assert result.extra["served_model"] == "clef-flash"
path, body, _ = server.state["requests"][-1]
assert path == "/v1/systemone"
assert body["model"] == "clef-flash"
assert body["state"] == "the user said hello"
question = body["questions"]["decision"]
assert question["type"] == "choice"
assert question["instructions"] == "Which category handles this request?"
assert question["criteria"] == {
"response": "description for response",
"calendar": "description for calendar",
}
# keep_alive is omitted unless configured.
assert "keep_alive" not in body
def test_call_sends_a_configured_keep_alive(ollama):
server, base = ollama
_engine(base, keep_alive="5m").call(_decision("a", "b"))
_, body, _ = server.state["requests"][-1]
assert body["keep_alive"] == "5m"
def test_call_sends_null_for_a_bare_label(ollama):
server, base = ollama
request = DecisionRequest(
state="state",
question="question",
options=[Option("a", ""), Option("b", " ")],
)
_engine(base).call(request)
_, body, _ = server.state["requests"][-1]
assert body["questions"]["decision"]["criteria"] == {"a": None, "b": None}
def test_call_normalizes_an_unnormalized_distribution(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {"decision": {"type": "choice", "probabilities": {"a": 0.4, "b": 0.4}}}
}
result = _engine(base).call(_decision("a", "b"))
assert result.probs == pytest.approx({"a": 0.5, "b": 0.5})
def test_call_rejects_mismatched_probability_keys(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {"decision": {"type": "choice", "probabilities": {"a": 1.0}}}
}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_a_choice_outside_the_requested_options(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {
"decision": {
"type": "choice",
"choice": "other",
"probabilities": {"a": 0.8, "b": 0.2},
}
}
}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_all_zero_distribution(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {"decision": {"type": "choice", "probabilities": {"a": 0.0, "b": 0.0}}}
}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_out_of_range_probability(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {"decision": {"type": "choice", "probabilities": {"a": 1.5, "b": 0.5}}}
}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_http_error_with_the_ollama_error_body(ollama):
server, base = ollama
server.state["systemone_status"] = 400
with pytest.raises(EngineUnavailable, match="400"):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_missing_answer(ollama):
server, base = ollama
server.state["systemone_response"] = {"answers": {}}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_requires_at_least_two_options(ollama):
_, base = ollama
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a"))
def test_call_requires_a_non_empty_state(ollama):
_, base = ollama
request = DecisionRequest(
state=" ",
question="q",
options=[Option("a", "a"), Option("b", "b")],
)
with pytest.raises(EngineUnavailable):
_engine(base).call(request)
def test_call_sends_bearer_token(ollama):
server, base = ollama
_engine(base, api_key="secret").call(_decision("a", "b"))
_, _, headers = server.state["requests"][-1]
assert headers.get("authorization") == "Bearer secret"
def test_generate_is_unavailable(ollama):
_, base = ollama
with pytest.raises(EngineUnavailable):
_engine(base).generate([{"role": "user", "content": "hi"}])
def test_warm_probes_ollama_native_endpoints_and_marks_loaded(ollama):
server, base = ollama
engine = _engine(base, context_tokens=0)
assert engine.loaded is False
engine.warm()
assert engine.loaded is True
assert "/api/version" in server.state["gets"]
assert [path for path, _, _ in server.state["requests"]] == ["/api/show"]
# context_tokens=0 follows the model's real num_ctx from /api/show.
assert engine.context_tokens == 16384
def test_warm_falls_back_to_the_architecture_context_length(ollama):
server, base = ollama
server.state["show_response"] = {
"capabilities": ["decision"],
"parameters": "",
"model_info": {"clef.context_length": 8192},
}
engine = _engine(base, context_tokens=0)
engine.warm()
assert engine.context_tokens == 8192
def test_warm_keeps_an_explicit_context_window(ollama):
server, base = ollama
engine = _engine(base, context_tokens=4096)
engine.warm()
assert engine.context_tokens == 4096
def test_warm_rejects_a_model_without_the_decision_capability(ollama):
server, base = ollama
server.state["show_response"] = {
"capabilities": ["completion", "thinking"],
"parameters": "num_ctx 4096",
}
with pytest.raises(EngineUnavailable, match="decision"):
_engine(base).warm()
def test_warm_rejects_a_missing_model(ollama):
server, base = ollama
server.state["show_status"] = 404
with pytest.raises(EngineUnavailable):
_engine(base).warm()
def test_warm_rejects_an_unreachable_server():
engine = OllamaSystemOneEngine(
OllamaSystemOneConfig(
base_url="http://127.0.0.1:1", model="clef-flash", timeout=1.0
)
)
with pytest.raises(EngineUnavailable):
engine.warm()
def test_unreachable_endpoint_raises_engine_unavailable():
engine = OllamaSystemOneEngine(
OllamaSystemOneConfig(
base_url="http://127.0.0.1:1", model="clef-flash", timeout=1.0
)
)
with pytest.raises(EngineUnavailable):
engine.call(_decision("a", "b"))
+2
View File
@@ -139,6 +139,8 @@ def test_expected_seeds_exist():
assert "time.set_alarm" in ids
assert "nextcloud.create_task" in ids
assert "calculator.calculate" in ids
assert "skills.list_categories" in ids
assert "skills.list_skills" in ids
assert "browser.open_page" in ids
assert "browser.read_page" in ids
assert "browser.screenshot" in ids
+144
View File
@@ -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"]
+56
View File
@@ -87,6 +87,7 @@ def test_minimum_plan_installs_nothing_heavy():
assert plan["install_simplex_forward"] is False
assert plan["install_browser"] is False
assert plan["install_voice"] is False
assert plan["install_transcribe"] is False
assert plan["packs"] == ["essentials"]
assert plan["pack_requirements"] == []
@@ -151,6 +152,23 @@ def test_maximum_config_enables_everything():
assert "llm_api_key" not in secrets
def test_ollama_engine_answers_emit_the_ollama_block():
answers = Answers(
engine_provider="ollama",
ollama_base_url="http://10.0.0.9:11434",
ollama_model="clef-flash",
ollama_api_key="ok",
)
config = build_config(answers, _packs())
assert config["engine"]["provider"] == "ollama"
assert config["engine"]["ollama"]["base_url"] == "http://10.0.0.9:11434"
assert config["engine"]["ollama"]["model"] == "clef-flash"
assert config["engine"]["ollama"]["api_key"] == "!secret engine_ollama_api_key"
assert validate_config(config, _packs()) == []
assert build_plan(answers, _packs())["install_engine"] is False
assert build_secrets(answers)["engine_ollama_api_key"] == "ok"
def test_simplex_gateway_without_pack_still_needs_the_binary():
answers = Answers(gateways=["simplex"])
plan = build_plan(answers, _packs())
@@ -177,6 +195,41 @@ def test_gateway_platforms_exclude_voice():
assert plan["install_gateway_service"] is True
def test_lxmf_voice_opts_into_transcription_dep():
answers = Answers(gateways=["lxmf"], lxmf_voice=True)
config = build_config(answers, _packs())
assert config["gateway"]["lxmf"]["voice"]["enabled"] is True
assert config["gateway"]["lxmf"]["voice"]["reply_with_voice"] is True
assert validate_config(config, _packs()) == []
plan = build_plan(answers, _packs())
assert plan["install_transcribe"] is True
# A voice reply also pulls the Piper TTS deps.
assert plan["install_lxmf_tts"] is True
# The rerun path re-derives the same plan from the written config.
assert plan_from_config(config, _packs())["install_transcribe"] is True
assert plan_from_config(config, _packs())["install_lxmf_tts"] is True
def test_lxmf_voice_transcribe_only_skips_tts_dep():
answers = Answers(gateways=["lxmf"], lxmf_voice=True, lxmf_voice_reply=False)
config = build_config(answers, _packs())
assert config["gateway"]["lxmf"]["voice"]["enabled"] is True
assert config["gateway"]["lxmf"]["voice"]["reply_with_voice"] is False
plan = build_plan(answers, _packs())
assert plan["install_transcribe"] is True
assert plan["install_lxmf_tts"] is False
assert plan_from_config(config, _packs())["install_lxmf_tts"] is False
def test_lxmf_without_voice_does_not_install_transcription():
answers = Answers(gateways=["lxmf"])
config = build_config(answers, _packs())
assert config["gateway"]["lxmf"]["voice"]["enabled"] is False
assert build_plan(answers, _packs())["install_transcribe"] is False
assert build_plan(answers, _packs())["install_lxmf_tts"] is False
# --------------------------------------------------------------------------- #
# Interview branching
# --------------------------------------------------------------------------- #
@@ -201,6 +254,7 @@ def test_interview_collects_authoring_endpoints_and_packs():
"bob", # nextcloud username
"pw", # nextcloud app password
"b", # gateways: lxmf
"3", # lxmf voice: transcribe + reply with voice
"Europe/Paris", # timezone
]
)
@@ -223,6 +277,8 @@ def test_interview_collects_authoring_endpoints_and_packs():
assert answers.packs == ["essentials", "simplex", "nextcloud"]
assert answers.nextcloud_url == "https://nc.example"
assert answers.gateways == ["lxmf"]
assert answers.lxmf_voice is True
assert answers.lxmf_voice_reply is True
assert answers.timezone == "Europe/Paris"
+74
View File
@@ -40,6 +40,7 @@ from semif_agent.skills import (
CreateCategory,
CreateSkill,
Skill,
SkillCatalog,
SkillDraft,
SkillStore,
build_category_prompt,
@@ -180,6 +181,79 @@ def test_scheduler_sizes_artifact_budgets_from_engine_context(tmp_path):
assert scheduler.max_test_chars == scheduler.max_body_chars
def test_skill_catalog_lists_categories_and_skills():
"""The read-only catalog reports the tree's categories and one category's
leaves, and follows the live provider."""
tree = {
"time": [
Skill(name="now", category="time", description="time"),
Skill(name="date", category="time", description="date"),
],
"calculator": [Skill(name="calculate", category="calculator", description="math")],
}
catalog = SkillCatalog(lambda: tree)
assert set(catalog.categories()) == {"time", "calculator"}
assert catalog.skills("time") == ["date", "now"]
assert catalog.skills("missing") == []
# A skill added after construction is still listed (the provider is live).
tree["new"] = [Skill(name="thing", category="new", description="d")]
assert "new" in catalog.categories()
def test_scheduler_exposes_a_read_only_catalog(tmp_path):
"""The scheduler supplies the catalog on the run context, but reserves
`admin` for the built-in housekeeping meta skills."""
scheduler = _scheduler(tmp_path)
assert scheduler.catalog is not None
categories = scheduler.catalog.categories()
assert "housekeeping" in categories and "response" in categories
assert "delete_skill" in scheduler.catalog.skills("housekeeping")
# An ordinary body sees the catalog but not the mutating admin surface.
housekeeping = next(
s for s in scheduler.tree["housekeeping"] if s.name == "delete_skill"
)
ordinary = Skill(
name="probe",
category="tracking",
description="Probe.",
act=lambda ctx, request: ActionResult(action_log="ok", new_state="x"),
)
house_ctx = scheduler.runner._skill_context(housekeeping, Request("x"))
plain_ctx = scheduler.runner._skill_context(ordinary, Request("x"))
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):
"""The gate ingests the whole body plus the inventory and goal, and never
the raw user request (the truncation bug and the PII path, both fixed)."""
+526 -3
View File
@@ -10,7 +10,8 @@ non-`b"SIL"` frame speech, and the fake STT returns a fixed string.
"""
from semif_agent.cli import _build_gateway_adapter, _resolve_platforms
from semif_agent.gateway.voice import VoiceAdapter
from semif_agent.gateway.base import OutboundMessage
from semif_agent.gateway.voice import VoiceAdapter, _is_stop_command
from semif_agent.voice_transport import VoiceDaemon, VoiceEngines
@@ -26,6 +27,9 @@ class FakeAudio:
self.writes = []
self.closed = False
self.input_opens = 0
#: Optional hook run at the start of `play` (to simulate a barge-in
#: landing mid-playback by setting the `stop_event`).
self.on_play = None
def open_input(self, sample_rate, frame_ms, device=""):
self.input_opens += 1
@@ -41,6 +45,14 @@ class FakeAudio:
def write(self, pcm16, sample_rate):
self.writes.append((pcm16, sample_rate))
def play(self, pcm16, sample_rate, stop_event=None):
if self.on_play is not None:
self.on_play(stop_event)
if stop_event is not None and stop_event.is_set():
return False
self.writes.append((pcm16, sample_rate))
return True
def flush(self):
pass # the scripted `frames` are input, not a capture buffer
@@ -327,8 +339,12 @@ def test_watchdog_disabled_uses_blocking_read(monkeypatch):
# ---- half-duplex / speaking ------------------------------------------------
def test_frames_ignored_while_speaking():
daemon, engines = make_daemon([b"WAKE", b"speech", b"SIL"])
def test_frames_ignored_while_speaking_when_barge_in_disabled():
# Strict half-duplex: with barge-in off the wake word is not even scored
# while a reply is playing, so the agent never transcribes its own voice.
daemon, engines = make_daemon(
[b"WAKE", b"speech", b"SIL"], config={"barge_in": {"enabled": False}}
)
daemon._speaking.set()
heard = []
daemon.run(heard.append)
@@ -336,6 +352,83 @@ def test_frames_ignored_while_speaking():
assert engines.stt.calls == []
def test_barge_in_wake_aborts_playback_and_captures_command():
# A reply is playing; the wake word fires over it -> the daemon stops the
# playback, tells the front end (on_barge_in True then False), and captures
# the command that follows.
daemon, engines = make_daemon([b"WAKE", b"command", b"SIL", b"SIL"])
events = []
daemon._event = lambda kind, **kw: events.append(kind)
barges = []
def on_barge(active):
barges.append(active)
if active:
daemon._speaking.clear() # the interrupted playback has stopped
daemon.on_barge_in = on_barge
daemon._speaking.set() # a reply is playing when the wake word lands
heard = []
daemon.run(heard.append)
assert heard == ["hello"]
assert barges == [True, False]
assert "voice_barge_in" in events
assert "voice_wake" not in events # barge-in, not a fresh wake
def test_barge_in_threshold_gates_interruption():
# A barge-in threshold above the wake score means the reply is not
# interrupted (the agent's own TTS cannot self-trigger a barge-in).
daemon, engines = make_daemon(
[b"WAKE", b"command", b"SIL", b"SIL"],
config={"barge_in": {"threshold": 2.0}}, # FakeWake scores 1.0
)
daemon._speaking.set()
heard = []
daemon.run(heard.append)
assert heard == []
assert engines.stt.calls == []
def test_barge_in_without_command_releases_mute():
# The wake word interrupts, but no command follows: the listening session
# ends and the mute is lifted (the front end is not left muted).
daemon, engines = make_daemon([b"WAKE", b"SIL", b"SIL", b"SIL"])
daemon._speaking.set()
def on_barge(active):
if active:
daemon._speaking.clear()
daemon.on_barge_in = on_barge
daemon.run(lambda text: None)
assert daemon._mute.is_set() is False
def test_speak_muted_while_barge_in():
daemon, engines = make_daemon([])
events = []
daemon._event = lambda kind, **kw: events.append(kind)
daemon.set_muted(True)
daemon.speak("should not be spoken")
assert engines.tts.spoken == []
assert engines.audio.writes == []
assert "voice_speak_suppressed" in events
def test_speak_interrupted_mid_playback():
daemon, engines = make_daemon([])
events = []
daemon._event = lambda kind, **kw: events.append(kind)
def on_play(stop_event):
stop_event.set() # a barge-in lands while the buffer is playing
engines.audio.on_play = on_play
daemon.speak("a long reply")
assert "voice_speak_interrupted" in events
def test_speak_synthesizes_and_plays():
daemon, engines = make_daemon([])
daemon.speak(" hello there ")
@@ -438,6 +531,95 @@ def test_adapter_is_result_only():
assert VoiceAdapter({}).result_only is True
# ---- barge-in (adapter classification) -------------------------------------
def test_is_stop_command():
assert _is_stop_command("Stop.") is True
assert _is_stop_command("cancel") is True
assert _is_stop_command("stop please") is True
assert _is_stop_command("shut up already") is True
assert _is_stop_command(" Quiet! ") is True
assert _is_stop_command("never mind") is True
# A longer utterance is a real command, not a stop.
assert _is_stop_command("stop the timer") is False
assert _is_stop_command("shut the door") is False
assert _is_stop_command("turn on the lights") is False
assert _is_stop_command("") is False
def test_adapter_barge_in_stop_drops_replies_and_does_not_forward():
import queue
adapter = VoiceAdapter({})
seen = []
adapter._on_inbound = seen.append
outbound: "queue.Queue" = queue.Queue()
outbound.put(OutboundMessage("voice", "one"))
outbound.put(OutboundMessage("voice", "two"))
adapter._outbound = outbound
events = []
adapter.daemon._event = lambda kind, **kw: events.append(kind)
adapter.daemon.set_muted(True)
adapter._barged_in = True
adapter._on_utterance("stop")
adapter._handle(adapter._inbound.get())
assert seen == [] # never submitted as a request
assert outbound.empty() # the queued replies were dropped
assert "gateway_barge_in_stop" in events
assert "gateway_speech_dropped" in events
assert adapter.daemon._mute.is_set() is False # unmuted for later replies
def test_adapter_barge_in_stop_preserves_shutdown_sentinel():
import queue
adapter = VoiceAdapter({})
adapter._on_inbound = lambda message: None
outbound: "queue.Queue" = queue.Queue()
outbound.put(OutboundMessage("voice", "stale"))
outbound.put(None)
adapter._outbound = outbound
adapter._barged_in = True
adapter._on_utterance("cancel")
adapter._handle(adapter._inbound.get())
# The stale reply is dropped but the pump's sentinel is preserved.
assert outbound.get() is None
def test_adapter_barge_in_new_command_is_forwarded():
adapter = VoiceAdapter({})
seen = []
adapter._on_inbound = seen.append
adapter.daemon.set_muted(True)
adapter._barged_in = True
adapter._on_utterance("turn on the lights")
message = adapter._inbound.get()
assert message.raw.get("barge_in") is True
adapter._handle(message)
assert [m.text for m in seen] == ["turn on the lights"]
assert adapter.daemon._mute.is_set() is False
def test_adapter_normal_utterance_is_not_a_barge_in():
adapter = VoiceAdapter({})
seen = []
adapter._on_inbound = seen.append
adapter._on_utterance("hello")
message = adapter._inbound.get()
assert message.raw.get("barge_in") is not True
adapter._handle(message)
assert [m.text for m in seen] == ["hello"]
def test_adapter_on_barge_in_callback_sets_flag():
adapter = VoiceAdapter({})
adapter._on_barge_in(True)
assert adapter._barged_in is True
adapter._on_barge_in(False)
assert adapter._barged_in is False
# ---- CLI wiring ------------------------------------------------------------
@@ -459,6 +641,144 @@ def test_resolve_platforms_includes_enabled_voice():
# ---- wake cue (beep) -------------------------------------------------------
def test_transcription_requirements_never_raises():
from semif_agent.voice_transport import check_transcription_requirements
ok, hint = check_transcription_requirements()
assert isinstance(ok, bool)
if not ok:
assert "faster-whisper" in hint
def test_check_codec2_requirements_never_raises():
from semif_agent.voice_transport import check_codec2_requirements
ok, hint = check_codec2_requirements()
assert isinstance(ok, bool)
if not ok:
assert "pycodec2" in hint
def test_decode_codec2_without_a_full_frame_is_none():
from semif_agent.voice_transport import decode_codec2
# Nothing to decode (shorter than a frame, empty, or no bitrate) -> None,
# whether or not pycodec2 is installed.
assert decode_codec2(b"x", 2400) is None
assert decode_codec2(b"", 2400) is None
assert decode_codec2(b"data", 0) is None
def test_decode_codec2_uses_bindings(monkeypatch):
import sys
import types
import pytest
np = pytest.importorskip("numpy")
calls = []
class FakeCodec2:
def __init__(self, rate):
self.rate = rate
def bytes_per_frame(self):
return 4
def samples_per_frame(self):
return 8
def decode(self, data):
calls.append(data)
return np.full(8, 7, dtype=np.int16)
fake = types.ModuleType("pycodec2")
fake.Codec2 = FakeCodec2
monkeypatch.setitem(sys.modules, "pycodec2", fake)
from semif_agent.voice_transport import decode_codec2
pcm = decode_codec2(b"aaaa" * 2, 2400) # two 4-byte frames
assert len(pcm) == 2 * 8 * 2 # frames * samples/frame * 2 bytes
assert calls == [b"aaaa", b"aaaa"]
assert pcm[:2] == b"\x07\x00"
def test_pcm_to_wav_is_a_readable_wav():
import io
import wave
from semif_agent.voice_transport import pcm_to_wav
pcm = b"\x01\x00\x02\x00"
data = pcm_to_wav(pcm, 8000)
assert data[:4] == b"RIFF"
with wave.open(io.BytesIO(data), "rb") as wav:
assert wav.getnchannels() == 1
assert wav.getsampwidth() == 2
assert wav.getframerate() == 8000
assert wav.readframes(2) == pcm
# ---- voice replies (Piper + Opus/OGG) --------------------------------------
def test_synthesis_requirements_never_raises():
from semif_agent.voice_transport import check_synthesis_requirements
ok, hint = check_synthesis_requirements()
assert isinstance(ok, bool)
if not ok:
assert "piper" in hint
def test_build_synthesizer_reads_the_tts_block(monkeypatch):
import semif_agent.voice_transport as vt
captured = {}
class FakePiper:
def __init__(self, voice, speaker_id=0, length_scale=1.0, volume=1.0):
captured.update(
voice=voice, speaker_id=speaker_id,
length_scale=length_scale, volume=volume,
)
monkeypatch.setattr(vt, "PiperSynthesizer", FakePiper)
vt.build_synthesizer(
{"tts": {"voice": "en_US-lessac-medium", "speaker_id": 3, "length_scale": 0.9}}
)
assert captured["voice"] == "en_US-lessac-medium"
assert captured["speaker_id"] == 3
assert captured["length_scale"] == 0.9
def test_pcm_to_opus_ogg_empty_input_is_empty():
from semif_agent.voice_transport import pcm_to_opus_ogg
assert pcm_to_opus_ogg(b"", 22050) == b""
assert pcm_to_opus_ogg(b"\x01", 22050) == b""
def test_pcm_to_opus_ogg_encodes_when_pyav_is_present():
import pytest
pytest.importorskip("av")
import io
import av
from semif_agent.voice_transport import pcm_to_opus_ogg
# 0.5 s of 22.05 kHz silence -> resampled + encoded to OGG/Opus.
pcm = b"\x00\x00" * 11025
data = pcm_to_opus_ogg(pcm, 22050)
assert data[:4] == b"OggS"
container = av.open(io.BytesIO(data))
stream = container.streams.audio[0]
assert stream.codec_context.name == "opus"
assert stream.sample_rate == 48000
def test_tone_pcm_length():
from semif_agent.voice_transport import _tone_pcm
@@ -607,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 == []