Compare commits

...
4 Commits
Author SHA1 Message Date
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
27 changed files with 2068 additions and 97 deletions

No files matched your search

+140 -16
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 recall never skips the actionability guard or feeds the
monotonic-progress guard; monotonic-progress guard;
housekeeping meta skills (delete/clear-config/regen/cancel-build) 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 a tri-state mode (`new_skill_creation`: deny/allow/ask, **deny by
default**) with a default**) with a
per-category override in the category config, with 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 a run paused for input is resumed by re-invoking act with the
answer on request.user_input; a answer on request.user_input; a
contract variable the runner cannot satisfy pauses BEFORE 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 timers.py in-process timer/alarm service (TimerService) owned by the
scheduler and exposed on ActionContext.timers: a single scheduler and exposed on ActionContext.timers: a single
background thread fires scheduled timers on the host clock, background thread fires scheduled timers on the host clock,
@@ -276,7 +280,11 @@ gateway/ messenger COMMAND intake/reply — and nothing else. base.py:
SimplexAdapter — command simplex-chat daemon over its JSON SimplexAdapter — command simplex-chat daemon over its JSON
WebSocket API (lazy `websockets`, allowlist, batching, WebSocket API (lazy `websockets`, allowlist, batching,
structured `/_send`). lxmf.py: LxmfAdapter — LXMF/Reticulum 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 + VoiceAdapter — the local microphone front end (wake word +
speech-to-text + text-to-speech) over the neutral speech-to-text + text-to-speech) over the neutral
`semif_agent/voice_transport.py`; no remote peer and no `semif_agent/voice_transport.py`; no remote peer and no
@@ -337,9 +345,10 @@ simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway
lxmf_transport.py lxmf_transport.py
neutral LXMF (Reticulum) transport: one in-process Reticulum neutral LXMF (Reticulum) transport: one in-process Reticulum
instance + LXMF router, persisted delivery identity, announce instance + LXMF router, persisted delivery identity, announce
loop, inbound normalization, outbound send queue. Lazy `RNS`/ loop, inbound normalization (text + the `FIELD_AUDIO`/`AM_*`
`LXMF` imports keep the module stdlib-only. Knows nothing about Sideband PTT voice payload, via `parse_audio_field`), outbound
the scheduler or the gateway. send queue. Lazy `RNS`/`LXMF` imports keep the module
stdlib-only. Knows nothing about the scheduler or the gateway.
voice_transport.py voice_transport.py
neutral voice transport: a 16 kHz mono capture loop with an neutral voice transport: a 16 kHz mono capture loop with an
always-on wake word (openWakeWord), VAD endpointing always-on wake word (openWakeWord), VAD endpointing
@@ -647,6 +656,47 @@ CLI, unit tests (24) + integration tests (2).
and one scheduler (`--platform simplex,lxmf|all`). DMs only for the first cut; and one scheduler (`--platform simplex,lxmf|all`). DMs only for the first cut;
groups/attachments/reactions are future work. See "### gateway (messenger groups/attachments/reactions are future work. See "### gateway (messenger
intake)". 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` - **Voice gateway (wake word + STT + TTS)** (Oct 2026): `gateway/voice.py`
(`VoiceAdapter`, platform `voice`) is the local microphone front end over the (`VoiceAdapter`, platform `voice`) is the local microphone front end over the
neutral `semif_agent/voice_transport.py`: an always-on openWakeWord wake word, neutral `semif_agent/voice_transport.py`: an always-on openWakeWord wake word,
@@ -878,7 +928,12 @@ CLI, unit tests (24) + integration tests (2).
`--voice` / `--browser` additionally install those optional stacks `--voice` / `--browser` additionally install those optional stacks
(`requirements/voice.txt` + system `libportaudio2` + `alsa-utils`; (`requirements/voice.txt` + system `libportaudio2` + `alsa-utils`;
`packs/browser/requirements.txt` + a browser) even when the plan did not pick `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 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 `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 selected packs, the SemIf engine, and the simplex-chat binary). Idempotent and
@@ -906,7 +961,10 @@ CLI, unit tests (24) + integration tests (2).
`simplex_chat` ports/display names stay in `config.json`. The python dep pins `simplex_chat` ports/display names stay in `config.json`. The python dep pins
live in `requirements/` split by concern (committed): `core.txt` (the test live in `requirements/` split by concern (committed): `core.txt` (the test
runner, always), `engine.txt` (the local decision engine), `transports.txt` 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 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 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 Playwright pin); the install plan lists the selected/enabled packs that ship
@@ -1046,7 +1104,7 @@ CLI, unit tests (24) + integration tests (2).
never holds secrets, and a generated body with the same name replaces the pack never holds secrets, and a generated body with the same name replaces the pack
skill. The shipped packs: `nextcloud`, `simplex`, `outlook`, `browser` (each skill. The shipped packs: `nextcloud`, `simplex`, `outlook`, `browser` (each
owning its bridge), and `essentials` (the built-in local utilities `time` + 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 example (creates a CalDAV event through the Nextcloud bridge; derives the
title/date/time from the query, asks for title/date/time from the query, asks for
missing fields and resumes, resolves the target calendar with a SemIf choice missing fields and resumes, resolves the target calendar with a SemIf choice
@@ -1073,6 +1131,14 @@ CLI, unit tests (24) + integration tests (2).
roots/fractions/percentages, SemIf picks the operands when the request offers 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 more numbers than the operator consumes, and the answer is spelled out in words
for the ear (an inexact result is announced as "approximately ..."); 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. `tests/test_packs.py` keeps every pack skill honest.
- **Contract provenance.** Each authored body records the CODEGEN.md revision it - **Contract provenance.** Each authored body records the CODEGEN.md revision it
was written against. `skill_contract_ref()` (`codegen.py`) returns was written against. `skill_contract_ref()` (`codegen.py`) returns
@@ -1360,6 +1426,48 @@ CLI, unit tests (24) + integration tests (2).
Reticulum` and `LXMF.LXMRouter` install process signal handlers, which only Reticulum` and `LXMF.LXMRouter` install process signal handlers, which only
work on the main thread** — `run_gateway` calls `daemon.prepare()` on the main work on the main thread** — `run_gateway` calls `daemon.prepare()` on the main
thread before the transport threads start, and `run()` reuses it. 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.
- **Voice adapter** (`gateway/voice.py`): the local microphone front end. It is - **Voice adapter** (`gateway/voice.py`): the local microphone front end. It is
a policy layer over the neutral `semif_agent/voice_transport.py` (`VoiceDaemon`) a policy layer over the neutral `semif_agent/voice_transport.py` (`VoiceDaemon`)
— openWakeWord wake word → `webrtcvad` endpointing → faster-whisper — openWakeWord wake word → `webrtcvad` endpointing → faster-whisper
@@ -1481,15 +1589,22 @@ CLI, unit tests (24) + integration tests (2).
scheduler, no HTTP. scheduler, no HTTP.
- **Tests.** `tests/test_gateway.py` (stdlib): SimpleX adapter allowlist/auth, - **Tests.** `tests/test_gateway.py` (stdlib): SimpleX adapter allowlist/auth,
structured send command, batching (real `asyncio`), LXMF adapter structured send command, batching (real `asyncio`), LXMF adapter
allowlist/auth and batching (a `threading.Timer`), cross-platform pending-run allowlist/auth and batching (a `threading.Timer`), LXMF voice-message
guard and per-platform reply routing, and `GatewayService` routing against a transcription through an injected fake transcriber (Opus dispatch, Codec2
real `Scheduler` (lazy engine, unreachable LLM). 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 `tests/test_humanize.py` covers the optional result cleanup with an injected
fake `llm` client (rewrite, quote/whitespace normalization, fallback on fake `llm` client (rewrite, quote/whitespace normalization, fallback on
error/empty/runaway, disabled passthrough, and the global + error/empty/runaway, disabled passthrough, and the global +
per-platform gateway enable/disable wiring). per-platform gateway enable/disable wiring).
`tests/test_lxmf_transport.py` covers the neutral LXMF transport's `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 needed). `tests/test_simplex_ws.py` covers the neutral protocol layer (parse
shapes, accept ids, corrId round-trips, address show/create). shapes, accept ids, corrId round-trips, address show/create).
`tests/test_bridges.py` `tests/test_bridges.py`
@@ -1507,7 +1622,12 @@ CLI, unit tests (24) + integration tests (2).
service or driver). service or driver).
`tests/test_voice_gateway.py` drives the voice loop `tests/test_voice_gateway.py` drives the voice loop
with injected fake engines (wake gating, endpointing, half-duplex, with injected fake engines (wake gating, endpointing, half-duplex,
`speak` truncation/failure, adapter + CLI wiring) — no `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 hardware, network, or heavy packages. `tests/test_voice_record.py` covers the
recording helpers (`semif_agent/voice_train.py`) — prompt loading, WAV I/O, recording helpers (`semif_agent/voice_train.py`) — prompt loading, WAV I/O,
level math, the silence-endpointing loop, and the LJSpeech dataset writer — level math, the silence-endpointing loop, and the LJSpeech dataset writer —
@@ -1523,6 +1643,10 @@ CLI, unit tests (24) + integration tests (2).
system `libportaudio2` + `alsa-utils`); it is lazy-imported too, and `bootstrap.sh --voice` 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, 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 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) ### skill packs (bundles)
@@ -1567,8 +1691,8 @@ CLI, unit tests (24) + integration tests (2).
`semif_agent/config.py` `SHARED_BRIDGE_SCHEMA`. `semif_agent/config.py` `SHARED_BRIDGE_SCHEMA`.
- **Shipped packs.** `nextcloud`, `simplex`, `outlook`, `browser` (each owning - **Shipped packs.** `nextcloud`, `simplex`, `outlook`, `browser` (each owning
its bridge) and `essentials` (the built-in local utilities `time` + its bridge) and `essentials` (the built-in local utilities `time` +
`calculator`; no bridge) — each in its own repository. Adding a concern means `calculator` + `skills`; no bridge) — each in its own repository. Adding a
adding a pack repo, not editing `skills.py`. concern means adding a pack repo, not editing `skills.py`.
### bridges (third-party API services) ### 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), `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 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). 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 `ctx.catalog` is a **read-only** view of the agent's own skill tree for an
body must never touch it. 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. - `request` is the `Request` being handled.
- `ActionResult(action_log: str, new_state: str, needs_input: str | None = None, - `ActionResult(action_log: str, new_state: str, needs_input: str | None = None,
decisions: list = [])` is imported from `semif_agent.skills`; return that exact decisions: list = [])` is imported from `semif_agent.skills`; return that exact
+51 -8
View File
@@ -352,7 +352,9 @@ fine-tuning loop — it is not yet the fine-tune itself.
with prompt hashes, tokens and timing. with prompt hashes, tokens and timing.
- **Run lifecycle tracing** — `runs.jsonl` keyed by `run_id`, powering a - **Run lifecycle tracing** — `runs.jsonl` keyed by `run_id`, powering a
Redux-DevTools-style dashboard. 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 + - **Voice gateway** — a local microphone front end: wake word + speech-to-text +
text-to-speech, all local (openWakeWord / faster-whisper / Piper). text-to-speech, all local (openWakeWord / faster-whisper / Piper).
- **Standalone bridge services** — an optional token-guarded localhost HTTP - **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 - **Seeds** — shipped real starter skills: `nextcloud.create_event` (the
authoritative worked example), `nextcloud.next_event` (the user's Nextcloud authoritative worked example), `nextcloud.next_event` (the user's Nextcloud
calendar, through the bridge), `nextcloud.create_task` (Nextcloud task list), calendar, through the bridge), `nextcloud.create_task` (Nextcloud task list),
`simplex.next_message` / `simplex.send_message` / `simplex.connect_link`, and `simplex.next_message` / `simplex.send_message` / `simplex.connect_link`,
`calculator.calculate` (two operands, one SemIf-chosen operator, spoken answer). `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. - **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 - **Stdlib-only core** — SemIf/llama.cpp are lazy imports, so the package stays
importable and testable without the heavy engine installed. 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) pack list lives in the semif-packs index repo (see PACKGEN.md)
scripts/ bootstrap.sh, config_merge.py, voice-*.py, systemd/*.in scripts/ bootstrap.sh, config_merge.py, voice-*.py, systemd/*.in
requirements/ core.txt (test runner), engine.txt (local decision engine), requirements/ core.txt (test runner), engine.txt (local decision engine),
transports.txt (websockets/lxmf), voice.txt transports.txt (websockets/lxmf), voice.txt (microphone
(staging.txt = the union of the non-hardware files); 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 a pack's own deps live with the pack at
packs/<name>/requirements.txt packs/<name>/requirements.txt
tests/ stdlib unit tests + tests/integration (real engine + LLM) tests/ stdlib unit tests + tests/integration (real engine + LLM)
@@ -489,7 +496,8 @@ It then installs **only what those answers require**. Both ends of the spectrum
are reachable by the end of a run: are reachable by the end of a run:
- **minimum** — local SemIf 4B + `essentials` (canned replies, time/timers, - **minimum** — local SemIf 4B + `essentials` (canned replies, time/timers,
calculator). No account, no network, no gateway, no heavy downloads. calculator, skill listing). No account, no network, no gateway, no heavy
downloads.
- **maximum** — every pack, a remote Winnow engine, remote `llm`/`codegen` - **maximum** — every pack, a remote Winnow engine, remote `llm`/`codegen`
endpoints, and all gateways. endpoints, and all gateways.
@@ -509,8 +517,10 @@ The script:
4. creates `.runtime/venv` and installs only the needed dep files: 4. creates `.runtime/venv` and installs only the needed dep files:
`requirements/core.txt` always, `engine.txt` for a local engine, `requirements/core.txt` always, `engine.txt` for a local engine,
`transports.txt` when a SimpleX/LXMF transport is selected (`voice.txt` for `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` the voice stack, `transcribe.txt` when `gateway.lxmf.voice` is enabled —
— e.g. the browser pack's Playwright deps); 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/` 5. for a local engine, downloads/sha256-verifies the GGUF into `.runtime/models/`
and pre-fetches the HF tokenizer into `.runtime/hf/`; and pre-fetches the HF tokenizer into `.runtime/hf/`;
6. downloads/sha256-verifies the pinned `simplex-chat` binary **only** when a 6. downloads/sha256-verifies the pinned `simplex-chat` binary **only** when a
@@ -583,6 +593,7 @@ Key blocks:
| `queue` | `max_size` | | `queue` | `max_size` |
| `skill_bodies` / `skill_packs` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) | | `skill_bodies` / `skill_packs` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) |
| `gateway.simplex` | command gateway: ws_url, allowlist, batching | | `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 | | `gateway.voice` | voice gateway: wake/STT/TTS engines + models, audio devices, VAD |
| `bridges.simplex` | forwarding bridge: host/port/token/ws_url | | `bridges.simplex` | forwarding bridge: host/port/token/ws_url |
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) | | `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
@@ -718,6 +729,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 and an optional `propagation_node` enables store-and-forward. Add the printed
address as a contact in your LXMF client and DM it. 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 > **Gateway isolation is non-negotiable.** The gateway takes commands and sends
> replies — nothing else. It never reads history, shows or creates invite links, > replies — nothing else. It never reads history, shows or creates invite links,
> or composes messages. That is messaging UX and lives in the bridges. > or composes messages. That is messaging UX and lives in the bridges.
@@ -1028,6 +1065,12 @@ authoring a new pack (and a new bridge to back one).
cubes, square roots, cube roots, fractions, and percentages, and SemIf picks cubes, square roots, cube roots, fractions, and percentages, and SemIf picks
the operands when the request writes more numbers than the operation needs the operands when the request writes more numbers than the operation needs
(pure local compute, no config). (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).
--- ---
+24 -1
View File
@@ -157,7 +157,27 @@
"storage_path": "", "storage_path": "",
"home_channel": "", "home_channel": "",
"reply_prefix": "", "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,
"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": { "voice": {
"enabled": false, "enabled": false,
@@ -306,6 +326,9 @@
"packs": { "packs": {
"essentials": { "essentials": {
"enabled": true "enabled": true
},
"gutendex": {
"enabled": true
} }
} }
} }
+9
View File
@@ -175,6 +175,15 @@ Then on the gateway host set:
"gateway": { "voice": { "tts": { "voice": "<name>" } } } "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 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 integration** — a generated test passing proves mechanics, not that the voice
loads and sounds right. 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 # Voice (voice.txt) and browser (packs/browser/requirements.txt) stacks are
# hardware/optional. Voice is a repo file installed with # hardware/optional. Voice is a repo file installed with
# `scripts/bootstrap.sh --voice`; the browser deps live WITH their pack and are # `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 core.txt
-r engine.txt -r engine.txt
-r transports.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 sounddevice==0.5.6
onnxruntime==1.30.0 onnxruntime==1.30.0
faster-whisper==1.2.1 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 piper-tts==1.8.0
webrtcvad-wheels==2.0.14.post1 webrtcvad-wheels==2.0.14.post1
# openwakeword runtime deps (installed here because openwakeword is --no-deps). # 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 \ 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_PLATFORMS PLAN_BRIDGE_PACKS PLAN_INSTALL_ENGINE PLAN_BRIDGE_SVC \
PLAN_GATEWAY_SVC PLAN_SIMPLEX_BIN PLAN_SIMPLEX_FWD PLAN_BROWSER PLAN_VOICE \ 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' python3 - "$PLAN" <<'PY'
import json, sys import json, sys
p = json.load(open(sys.argv[1])) p = json.load(open(sys.argv[1]))
@@ -326,6 +326,8 @@ print("\x1f".join([
flag("install_simplex_forward"), flag("install_simplex_forward"),
flag("install_browser"), flag("install_browser"),
flag("install_voice"), flag("install_voice"),
flag("install_transcribe"),
flag("install_lxmf_tts"),
",".join(p.get("pack_requirements", [])), ",".join(p.get("pack_requirements", [])),
])) ]))
PY PY
@@ -350,7 +352,7 @@ NEED_TRANSPORTS=0
[[ ",$PLAN_GATEWAYS," == *",lxmf,"* ]] && NEED_TRANSPORTS=1 [[ ",$PLAN_GATEWAYS," == *",lxmf,"* ]] && NEED_TRANSPORTS=1
echo "== plan: engine=$PLAN_ENGINE | authoring=$PLAN_AUTHORING | packs=$PLAN_PACKS" 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}" echo " pack deps=${PLAN_PACK_REQS:-none}"
# The live config may be split (config.json includes config/*.json); merge it so # 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 "$PIP" install --no-deps openwakeword==0.6.0
fi 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 --------------------------------------- # --- stage 3c: pack-declared python deps ---------------------------------------
# A pack owns the python deps its skills/bridge need, shipped as # A pack owns the python deps its skills/bridge need, shipped as
# packs/<name>/requirements.txt (standard pip format). The install plan lists the # 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 || echo "WARN: voice model download failed; re-run scripts/voice-models.py" >&2
fi 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) -------------------- # --- stage 6: simplex-chat daemon binary (only when needed) --------------------
if [[ "$PLAN_SIMPLEX_BIN" = 1 ]]; then if [[ "$PLAN_SIMPLEX_BIN" = 1 ]]; then
SIMPLEX_BIN="$TOOLDIR/simplex-chat" SIMPLEX_BIN="$TOOLDIR/simplex-chat"
+8
View File
@@ -838,6 +838,14 @@ def _build_gateway_adapter(platform: str, cfg: dict, trace):
# Contain Reticulum's config + identity under the checkout's .runtime/. # Contain Reticulum's config + identity under the checkout's .runtime/.
cfg.setdefault("config_dir", str(REPO_ROOT / ".runtime" / "lxmf" / "reticulum")) cfg.setdefault("config_dir", str(REPO_ROOT / ".runtime" / "lxmf" / "reticulum"))
cfg.setdefault("storage_path", str(REPO_ROOT / ".runtime" / "lxmf" / "router")) 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) return LxmfAdapter(cfg, trace=trace)
if platform == "voice": if platform == "voice":
from .gateway.voice import VoiceAdapter from .gateway.voice import VoiceAdapter
+25 -1
View File
@@ -166,7 +166,31 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': '
'storage_path': {'default': '', 'type': 'str'}, 'storage_path': {'default': '', 'type': 'str'},
'home_channel': {'default': '', 'type': 'str'}, 'home_channel': {'default': '', 'type': 'str'},
'reply_prefix': {'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'},
'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'}, 'voice': {'enabled': {'default': False, 'type': 'bool'},
'chat_id': {'default': 'voice', 'type': 'str'}, 'chat_id': {'default': 'voice', 'type': 'str'},
'display_name': {'default': 'voice', 'type': 'str'}, 'display_name': {'default': 'voice', 'type': 'str'},
+4 -4
View File
@@ -51,10 +51,10 @@ class GatewayAdapter(ABC):
#: short platform name used in request sources (`"simplex:<chat_id>"`) #: short platform name used in request sources (`"simplex:<chat_id>"`)
name: str = "gateway" name: str = "gateway"
#: Spoken front ends (the voice gateway) set this so the service speaks only #: Front ends that should send only the skill's result line set this, so the
#: the skill's result line, not the scheduler's bookkeeping (queue/urgency #: service drops the scheduler's bookkeeping (queue/urgency status) and the
#: status) and not the `<skill>: ok —` wrapper. A per-platform config #: `<skill>: ok —` wrapper. The voice gateway and the LXMF gateway set it; a
#: `result_only` overrides it. Plain chat adapters leave it False. #: per-platform config `result_only` overrides it either way.
result_only: bool = False result_only: bool = False
@abstractmethod @abstractmethod
+349 -24
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 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 no external daemon and no event loop — Reticulum runs in-process on its own
threads, so batching uses a per-chat `threading.Timer`. 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 from __future__ import annotations
@@ -20,14 +46,50 @@ import queue
import threading import threading
from semif_agent.lxmf_transport import LxmfDaemon from semif_agent.lxmf_transport import LxmfDaemon
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
#: 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): class LxmfAdapter(GatewayAdapter):
name = "lxmf" 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 {} cfg = cfg or {}
self.allowed_users = [str(u) for u in cfg.get("allowed_users", []) 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)) self.allow_all_users = bool(cfg.get("allow_all_users", False))
@@ -51,8 +113,31 @@ class LxmfAdapter(GatewayAdapter):
) )
self.config_dir = config_dir self.config_dir = config_dir
self.storage_path = storage_path 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._buffers: dict[str, str] = {}
self._buffered: dict[str, InboundMessage] = {} self._buffered: dict[str, dict] = {}
self._timers: dict[str, threading.Timer] = {} self._timers: dict[str, threading.Timer] = {}
self._lock = threading.Lock() self._lock = threading.Lock()
self._on_inbound = None self._on_inbound = None
@@ -60,6 +145,9 @@ class LxmfAdapter(GatewayAdapter):
# ---- requirements ---- # ---- requirements ----
def check_requirements(self) -> tuple[bool, str | None]: 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() return self.daemon.check_requirements()
# ---- authorization ---- # ---- authorization ----
@@ -82,17 +170,20 @@ class LxmfAdapter(GatewayAdapter):
outbound: "queue.Queue[OutboundMessage | None]", outbound: "queue.Queue[OutboundMessage | None]",
) -> None: ) -> None:
self._on_inbound = on_inbound self._on_inbound = on_inbound
self._outbound = outbound
def _pump() -> None: def _pump() -> None:
# Translate the service's OutboundMessage queue onto the daemon's # Translate the service's OutboundMessage queue onto the daemon's
# (chat_id, text) queue without letting scheduler work touch the # (chat_id, text, audio) queue without letting scheduler work touch
# Reticulum callback threads. # the Reticulum callback threads. Synthesis runs here (off the router
# thread), so a slow Piper render never stalls the transport.
while True: while True:
message = outbound.get() message = outbound.get()
if message is None: if message is None:
self.daemon.enqueue(None) self.daemon.enqueue(None)
return return
self.daemon.enqueue(message.chat_id, message.text) audio = self._voice_reply(message)
self.daemon.enqueue(message.chat_id, message.text, audio=audio)
threading.Thread( threading.Thread(
target=_pump, name="lxmf-outbound-pump", daemon=True target=_pump, name="lxmf-outbound-pump", daemon=True
@@ -105,6 +196,7 @@ class LxmfAdapter(GatewayAdapter):
self._timers.clear() self._timers.clear()
for timer in timers: for timer in timers:
timer.cancel() timer.cancel()
self._voice_queue.put(None)
self.daemon.close() self.daemon.close()
# ---- inbound ---- # ---- inbound ----
@@ -121,23 +213,23 @@ class LxmfAdapter(GatewayAdapter):
display_name=display_name, display_name=display_name,
) )
return return
inbound = InboundMessage( audio = message.get("audio")
text=message.get("content") or "", if audio:
chat_id=source_hash, # A voice message puts the chat in voice-reply mode (when the reply
chat_type="dm", # path is on); a later text message reverts it.
contact_id=source_hash, if self.voice_enabled and self.reply_with_voice:
display_name=display_name, self._mark_voice_chat(source_hash)
raw=message.get("raw") or {}, self._handle_audio(message, audio)
) return
self._schedule_flush(inbound) self._unmark_voice_chat(source_hash)
self._schedule_flush(message)
def _schedule_flush(self, message: InboundMessage) -> None: def _schedule_flush(self, message: dict) -> None:
chat = message.chat_id chat = str(message.get("source_hash") or "")
text = message.get("content") or ""
with self._lock: with self._lock:
existing = self._buffers.get(chat) existing = self._buffers.get(chat)
self._buffers[chat] = ( self._buffers[chat] = f"{existing}\n{text}" if existing else text
f"{existing}\n{message.text}" if existing else message.text
)
self._buffered[chat] = message self._buffered[chat] = message
timer = self._timers.get(chat) timer = self._timers.get(chat)
if timer is not None: if timer is not None:
@@ -154,12 +246,245 @@ class LxmfAdapter(GatewayAdapter):
self._timers.pop(chat, None) self._timers.pop(chat, None)
if message is None or not text: if message is None or not text:
return 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")
self.daemon._event( self.daemon._event(
"gateway_message", "gateway_message",
contact_id=message.contact_id, contact_id=source_hash,
display_name=message.display_name, display_name=display_name,
chars=len(text), chars=len(text),
) )
if self._on_inbound is not None: if self._on_inbound is None:
self._on_inbound(message) 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
+216 -15
View File
@@ -31,6 +31,96 @@ MessageHandler = Callable[[InboundDict], None]
#: Zero-argument callback invoked once the router is ready to receive. #: Zero-argument callback invoked once the router is ready to receive.
ConnectedHandler = Callable[[], None] 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: def _as_text(value: Any) -> str:
"""Best-effort UTF-8 text for a `str`/`bytes`/`None` LXMF field.""" """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: if source is not None:
display_name = _as_text(getattr(source, "display_name", 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 { return {
"source_hash": source_hash, "source_hash": source_hash,
"display_name": display_name or None, "display_name": display_name or None,
"title": title, "title": title,
"content": content, "content": content,
"timestamp": getattr(message, "timestamp", None), "timestamp": getattr(message, "timestamp", None),
"fields": fields,
"audio": audio,
"raw": message, "raw": message,
} }
@@ -101,7 +203,10 @@ class LxmfDaemon:
"""One in-process Reticulum instance + LXMF router. """One in-process Reticulum instance + LXMF router.
`run(on_message)` blocks, announcing the delivery destination periodically `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), 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. drained by an internal pump thread. `address` is the bot's LXMF address.
@@ -138,9 +243,20 @@ class LxmfDaemon:
self._reticulum = None self._reticulum = None
self._destination = None self._destination = None
self._address = "" 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._stop = threading.Event()
self._on_message: MessageHandler | None = None 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 ---- # ---- requirements ----
@@ -216,6 +332,15 @@ class LxmfDaemon:
) )
except Exception as exc: except Exception as exc:
self._event("lxmf_propagation_error", message=str(exc)[:300]) 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) self._event("lxmf_ready", address=self._address)
return self._router return self._router
@@ -225,7 +350,7 @@ class LxmfDaemon:
threading.Thread( threading.Thread(
target=self._pump, name="lxmf-outbound-pump", daemon=True target=self._pump, name="lxmf-outbound-pump", daemon=True
).start() ).start()
self._announce() self._announce("startup")
if self.on_connected is not None: if self.on_connected is not None:
try: try:
self.on_connected() self.on_connected()
@@ -234,15 +359,75 @@ class LxmfDaemon:
"lxmf_error", phase="on_connected", message=str(exc)[:300] "lxmf_error", phase="on_connected", message=str(exc)[:300]
) )
while not self._stop.wait(self._announce_wait()): self._announce_loop()
self._announce()
def enqueue(self, chat_id: str | None, text: str = "") -> None: def _announce_loop(self) -> None:
"""Queue an outbound send. `chat_id=None` is the stop sentinel.""" """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: if chat_id is None:
self._outbound.put(None) self._outbound.put(None)
else: else:
self._outbound.put((str(chat_id), text)) self._outbound.put((str(chat_id), text, audio))
def close(self) -> None: def close(self) -> None:
self._stop.set() self._stop.set()
@@ -277,12 +462,13 @@ class LxmfDaemon:
return 3600.0 return 3600.0
return self.announce_interval return self.announce_interval
def _announce(self) -> None: def _announce(self, reason: str = "") -> None:
if self._router is None or self._destination is None: if self._router is None or self._destination is None:
return return
try: try:
self._router.announce(self._destination.hash) 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: except Exception as exc:
self._event("lxmf_error", phase="announce", message=str(exc)[:300]) self._event("lxmf_error", phase="announce", message=str(exc)[:300])
@@ -309,17 +495,27 @@ class LxmfDaemon:
item = self._outbound.get() item = self._outbound.get()
if item is None: if item is None:
return return
chat_id, text = item chat_id, text, audio = item
try: try:
self.send(chat_id, text) self.send(chat_id, text, audio=audio)
except Exception as exc: except Exception as exc:
self._event( self._event(
"lxmf_send_failed", contact=chat_id, message=str(exc)[:300] "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). """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 Recalls the peer identity from the network; when the path is not yet
known it requests it and waits briefly. Raises (never silently drops) known it requests it and waits briefly. Raises (never silently drops)
when the destination cannot be resolved — a reply must be real. when the destination cannot be resolved — a reply must be real.
@@ -351,9 +547,14 @@ class LxmfDaemon:
if self.desired_method == "opportunistic" if self.desired_method == "opportunistic"
else LXMF.LXMessage.DIRECT 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._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 ---- # ---- tracing ----
+10 -1
View File
@@ -54,6 +54,7 @@ from .skills import (
CreateSkill, CreateSkill,
DeletedSkills, DeletedSkills,
Skill, Skill,
SkillCatalog,
SkillDraft, SkillDraft,
SkillStore, SkillStore,
apply_tombstones, apply_tombstones,
@@ -435,8 +436,16 @@ class Scheduler:
for category in disabled_categories(config, self.packs): for category in disabled_categories(config, self.packs):
self.tree.pop(category, None) self.tree.pop(category, None)
self.timers = TimerService(trace=self.trace, timezone=config.get("timezone")) self.timers = TimerService(trace=self.trace, timezone=config.get("timezone"))
# 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( self.ctx = ActionContext(
engine=self.engine, config=config, timers=self.timers, admin=self engine=self.engine,
config=config,
timers=self.timers,
admin=self,
catalog=self.catalog,
) )
self.runner = SkillRunner( self.runner = SkillRunner(
self.ctx, self.ctx,
+62
View File
@@ -99,6 +99,13 @@ class Answers:
# Gateway platforms to enable. # Gateway platforms to enable.
gateways: list[str] = field(default_factory=list) 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. # IANA timezone; empty uses the host zone.
timezone: str = "" timezone: str = ""
@@ -462,6 +469,29 @@ def run_interview(
default=answers.gateways, 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. # 6. Timezone.
output("") output("")
answers.timezone = _ask_text( answers.timezone = _ask_text(
@@ -568,6 +598,12 @@ def build_config(answers: Answers, packs: Sequence[SkillPack]) -> dict:
for platform in ("simplex", "lxmf", "voice"): for platform in ("simplex", "lxmf", "voice"):
gateway.setdefault(platform, {})["enabled"] = platform in answers.gateways gateway.setdefault(platform, {})["enabled"] = platform in answers.gateways
gateway.setdefault("humanize", {})["enabled"] = bool(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 return config
@@ -632,6 +668,17 @@ def build_plan(answers: Answers, packs: Sequence[SkillPack]) -> dict:
"install_simplex_forward": "simplex" in answers.packs, "install_simplex_forward": "simplex" in answers.packs,
"install_browser": "browser" in answers.packs, "install_browser": "browser" in answers.packs,
"install_voice": "voice" in answers.gateways, "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 +712,21 @@ def plan_from_config(config: dict, packs: Sequence[SkillPack]) -> dict:
"install_simplex_forward": "simplex" in enabled, "install_simplex_forward": "simplex" in enabled,
"install_browser": "browser" in enabled, "install_browser": "browser" in enabled,
"install_voice": "voice" in gateways, "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)
),
} }
+6 -1
View File
@@ -34,6 +34,7 @@ from .log import DecisionLog
from .skills import ( from .skills import (
CANNED_CATEGORIES, CANNED_CATEGORIES,
DETERMINISTIC_CATEGORIES, DETERMINISTIC_CATEGORIES,
HOUSEKEEPING_CATEGORY,
ActionContext, ActionContext,
Skill, Skill,
SkillStore, SkillStore,
@@ -147,7 +148,11 @@ class SkillRunner:
engine=self.ctx.engine, engine=self.ctx.engine,
config=merged, config=merged,
timers=self.ctx.timers, timers=self.ctx.timers,
admin=self.ctx.admin, # `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]: def _unresolved(self, skill: Skill, request: Request) -> list[str]:
+28 -1
View File
@@ -47,8 +47,35 @@ class ActionContext:
timers: TimerService | None = None timers: TimerService | None = None
# The scheduler, exposed to built-in meta skills (housekeeping) so they can # 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 # 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 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: def _noop_act(ctx: ActionContext, request: Request) -> ActionResult:
+275 -19
View File
@@ -48,6 +48,28 @@ _REQUIRED_MODULES: tuple[tuple[str, str], ...] = (
("onnxruntime", "onnxruntime"), ("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) # Engine interfaces (fakes are injected in tests)
@@ -83,6 +105,15 @@ class Transcriber:
def transcribe(self, pcm16: bytes) -> str: def transcribe(self, pcm16: bytes) -> str:
raise NotImplementedError 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: def close(self) -> None:
pass pass
@@ -236,6 +267,10 @@ class WhisperTranscriber(Transcriber):
self._model = WhisperModel(str(model or "base.en"), device=str(device or "cpu"), self._model = WhisperModel(str(model or "base.en"), device=str(device or "cpu"),
compute_type=str(compute_type or "int8")) 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: def transcribe(self, pcm16: bytes) -> str:
import numpy as np import numpy as np
@@ -246,7 +281,25 @@ class WhisperTranscriber(Transcriber):
beam_size=self.beam_size, beam_size=self.beam_size,
vad_filter=self.vad_filter, 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): class PiperSynthesizer(Synthesizer):
@@ -572,10 +625,228 @@ def _build_vad(cfg: dict) -> VadGate:
return EnergyVadGate(threshold=float(vad_cfg.get("energy_threshold", 200.0))) 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: def build_engines(cfg: dict, trace=None) -> VoiceEngines:
"""Construct the real engine bundle from a `gateway.voice` config block.""" """Construct the real engine bundle from a `gateway.voice` config block."""
wake_cfg = cfg.get("wake", {}) or {} wake_cfg = cfg.get("wake", {}) or {}
stt_cfg = cfg.get("stt", {}) or {}
tts_cfg = cfg.get("tts", {}) or {} tts_cfg = cfg.get("tts", {}) or {}
audio_cfg = cfg.get("audio", {}) or {} audio_cfg = cfg.get("audio", {}) or {}
@@ -584,11 +855,6 @@ def build_engines(cfg: dict, trace=None) -> VoiceEngines:
str(wake_cfg.get("model_dir", "") or ""), str(wake_cfg.get("model_dir", "") or ""),
(".onnx", ".tflite"), (".onnx", ".tflite"),
) )
tts_voice = resolve_model_path(
str(tts_cfg.get("voice", "") or ""),
str(tts_cfg.get("voice_dir", "") or ""),
(".onnx",),
)
return VoiceEngines( return VoiceEngines(
wake=OpenWakeWordDetector( wake=OpenWakeWordDetector(
wake_model, wake_model,
@@ -596,18 +862,8 @@ def build_engines(cfg: dict, trace=None) -> VoiceEngines:
inference_framework=str(wake_cfg.get("inference_framework", "onnx")), inference_framework=str(wake_cfg.get("inference_framework", "onnx")),
), ),
vad=_build_vad(cfg), vad=_build_vad(cfg),
stt=WhisperTranscriber( stt=build_transcriber(cfg),
model=str(stt_cfg.get("model", "base.en") or "base.en"), tts=_build_piper(tts_cfg),
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),
),
audio=SoundDeviceAudio( audio=SoundDeviceAudio(
input_device=str(audio_cfg.get("input_device", "") or ""), input_device=str(audio_cfg.get("input_device", "") or ""),
output_device=str(audio_cfg.get("output_device", "") or ""), output_device=str(audio_cfg.get("output_device", "") or ""),
+345
View File
@@ -10,6 +10,7 @@ live-daemon integration concern, not a unit test.
import asyncio import asyncio
import json import json
import queue
import time import time
from semif_agent.cli import _gateway_address_callback from semif_agent.cli import _gateway_address_callback
@@ -549,6 +550,350 @@ def test_lxmf_denies_unknown_sender_without_dispatch():
assert seen == [] 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
# ---- service: multiple platforms ---- # ---- service: multiple platforms ----
class FakeLxmfAdapter: class FakeLxmfAdapter:
+138 -1
View File
@@ -7,7 +7,14 @@ a live-integration concern.
""" """
from semif_agent.gateway.lxmf import LxmfAdapter 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 ---- # ---- requirements ----
@@ -94,3 +101,133 @@ def test_normalize_message_handles_none_content():
assert normalized["source_hash"] == "" assert normalized["source_hash"] == ""
assert normalized["content"] == "" assert normalized["content"] == ""
assert normalized["title"] == "" 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
+2
View File
@@ -139,6 +139,8 @@ def test_expected_seeds_exist():
assert "time.set_alarm" in ids assert "time.set_alarm" in ids
assert "nextcloud.create_task" in ids assert "nextcloud.create_task" in ids
assert "calculator.calculate" 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.open_page" in ids
assert "browser.read_page" in ids assert "browser.read_page" in ids
assert "browser.screenshot" in ids assert "browser.screenshot" in ids
+39
View File
@@ -87,6 +87,7 @@ def test_minimum_plan_installs_nothing_heavy():
assert plan["install_simplex_forward"] is False assert plan["install_simplex_forward"] is False
assert plan["install_browser"] is False assert plan["install_browser"] is False
assert plan["install_voice"] is False assert plan["install_voice"] is False
assert plan["install_transcribe"] is False
assert plan["packs"] == ["essentials"] assert plan["packs"] == ["essentials"]
assert plan["pack_requirements"] == [] assert plan["pack_requirements"] == []
@@ -177,6 +178,41 @@ def test_gateway_platforms_exclude_voice():
assert plan["install_gateway_service"] is True 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 # Interview branching
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
@@ -201,6 +237,7 @@ def test_interview_collects_authoring_endpoints_and_packs():
"bob", # nextcloud username "bob", # nextcloud username
"pw", # nextcloud app password "pw", # nextcloud app password
"b", # gateways: lxmf "b", # gateways: lxmf
"3", # lxmf voice: transcribe + reply with voice
"Europe/Paris", # timezone "Europe/Paris", # timezone
] ]
) )
@@ -223,6 +260,8 @@ def test_interview_collects_authoring_endpoints_and_packs():
assert answers.packs == ["essentials", "simplex", "nextcloud"] assert answers.packs == ["essentials", "simplex", "nextcloud"]
assert answers.nextcloud_url == "https://nc.example" assert answers.nextcloud_url == "https://nc.example"
assert answers.gateways == ["lxmf"] assert answers.gateways == ["lxmf"]
assert answers.lxmf_voice is True
assert answers.lxmf_voice_reply is True
assert answers.timezone == "Europe/Paris" assert answers.timezone == "Europe/Paris"
+45
View File
@@ -40,6 +40,7 @@ from semif_agent.skills import (
CreateCategory, CreateCategory,
CreateSkill, CreateSkill,
Skill, Skill,
SkillCatalog,
SkillDraft, SkillDraft,
SkillStore, SkillStore,
build_category_prompt, build_category_prompt,
@@ -180,6 +181,50 @@ def test_scheduler_sizes_artifact_budgets_from_engine_context(tmp_path):
assert scheduler.max_test_chars == scheduler.max_body_chars 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
def test_fidelity_gate_state_is_whole_body_without_the_request(tmp_path): 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 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).""" the raw user request (the truncation bug and the PII path, both fixed)."""
+138
View File
@@ -459,6 +459,144 @@ def test_resolve_platforms_includes_enabled_voice():
# ---- wake cue (beep) ------------------------------------------------------- # ---- 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(): def test_tone_pcm_length():
from semif_agent.voice_transport import _tone_pcm from semif_agent.voice_transport import _tone_pcm