Files
semif-agent/semif_agent/gateway/base.py
T
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

73 lines
2.5 KiB
Python

"""The messenger command-gateway adapter contract.
An adapter owns one command transport (SimpleX WebSocket, and later Telegram,
Signal, ...). It delivers inbound text as `InboundMessage` and drains outbound
replies from a stdlib queue. Everything about the SemIf scheduler — gating,
scoring, queueing, run ownership, questions, repairs — lives in `GatewayService`;
an adapter must not know it exists. Neither knows anything about messaging UX
(invite links, reading, composing): that is the bridge services' job.
The transport is intentionally a plain `queue.Queue`: the adapter's event loop
puts an outbound message into the queue, the service puts replies into it. This
keeps scheduler work (which is synchronous and can block on the decision engine)
off the adapter's event loop.
"""
from __future__ import annotations
import queue
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any, Callable
@dataclass
class InboundMessage:
"""One (possibly batched) inbound text message from an external chat."""
text: str
chat_id: str
chat_type: str = "dm" # dm | group
contact_id: str | None = None
display_name: str | None = None
raw: dict[str, Any] = field(default_factory=dict)
@dataclass
class OutboundMessage:
"""One reply destined for an external chat."""
chat_id: str
text: str
#: Callback the adapter invokes for each authorized inbound message.
InboundHandler = Callable[[InboundMessage], None]
class GatewayAdapter(ABC):
"""Transport contract for a messenger platform."""
#: short platform name used in request sources (`"simplex:<chat_id>"`)
name: str = "gateway"
#: Front ends that should send only the skill's result line set this, so the
#: service drops the scheduler's bookkeeping (queue/urgency status) and the
#: `<skill>: ok —` wrapper. The voice gateway and the LXMF gateway set it; a
#: per-platform config `result_only` overrides it either way.
result_only: bool = False
@abstractmethod
def check_requirements(self) -> tuple[bool, str | None]:
"""Return `(ok, install_hint)`. Must never raise on a missing dep."""
@abstractmethod
def run(self, on_inbound: InboundHandler, outbound: "queue.Queue[OutboundMessage | None]") -> None:
"""Block, delivering inbound messages and sending queued outbound ones.
A `None` sentinel in `outbound` asks `run` to return.
"""
def close(self) -> None:
"""Release transport resources. Best-effort; must not raise."""