Compare commits

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

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

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

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

`cli.build_engine` selects it, the setup interview and `--answers` accept
it, and the install plan skips the engine clone/GGUF/tokenizer for it.
Docs, config.example.json, and tests updated.
2026-11-11 02:57:53 +00:00
gabby 894a85ec2d read-aloud: stream a long text over the voice gateways
A skill that resolves a long text (a book) can hand it to the scheduler's
speech channel and return immediately; the gateway that owns the chat drains it
and streams it with text-to-speech until the user stops it.

- semif_agent/speech.py: SpeechService + ReadAloud. A bounded queue a front end
  drains, plus a per-source streaming predicate (set_stream_check/supports) so a
  skill asks before it posts one. Neutral and stdlib-only.
- semif_agent/reading.py: the bookmarks.json beside the saved books (load/save/
  read a key -> last offset, atomic write) and a deterministic speakable
  chunker at paragraph/sentence boundaries.
- Scheduler owns the channel (scheduler.speech); SkillRunner passes it into
  every run's ActionContext, so a body reaches it as ctx.speech.
- gateway/service: registers stream_ready as the channel's capability
  predicate, and surface() routes a drained read to the platform that owns the
  run (a non-streaming adapter is traced and skipped, never handed a message it
  would drop).
- gateway/voice: streams the saved text through the daemon's Piper voice chunk
  by chunk, writing the bookmark before each chunk; a barge-in "stop" or any new
  command ends it.
- gateway/lxmf: a read goes to a chat that last messaged by voice as a sequence
  of Sideband HQ voice messages (Piper -> Opus/OGG, backpressure so a stop is
  prompt), with the same bookmark-per-chunk resume; a "stop" message or any new
  command interrupts it.
- A run that registers a read is terminal (read_aloud_terminal): the read is the
  answer, so assess:outcome must not re-dispatch the request (which otherwise
  authored a spurious skill).
- config.example.json regenerated with the new voice/lxmf read blocks.
2026-10-17 23:29:53 +00:00
gabby faebe8a53a voice: wake-word barge-in (interrupt a spoken reply)
While a reply is speaking the wake word is still scored, so the user can
interrupt it. On a wake the daemon aborts the playback, mutes further
speech while the interrupt is captured/handled, and hands the following
command to the front end. A bare "stop"/"cancel" aborts the reply and
drops anything queued behind it; anything else runs as a new command.

- voice_transport: AudioIO.play(pcm, rate, stop_event); SoundDeviceAudio
  streams in ~50 ms chunks and aborts the output stream on a stop.
  VoiceDaemon gains barge_in.{enabled,wait_s,threshold} and the
  on_barge_in(active) callback; speak() drops text while muted and plays
  through the interruptible path.
- gateway/voice: tags the interrupt utterance (raw["barge_in"]),
  classifies stop vs new command (_is_stop_command), drops queued replies
  on stop, and unmutes once handled.
- config: gateway.voice.barge_in block; config.example.json regenerated.
- tests: wake-abort, mute release, threshold gate, stop/new-command
  classification, sentinel preservation.
2026-10-17 16:56:44 +00:00
27 changed files with 2875 additions and 103 deletions

No files matched your search

+142 -28
View File
@@ -199,6 +199,20 @@ timers.py in-process timer/alarm service (TimerService) owned by the
the gateway routes it to the originating chat, the dashboard the gateway routes it to the originating chat, the dashboard
shows pending/fired). Real local compute (`compute` transport), shows pending/fired). Real local compute (`compute` transport),
per-process, and deliberately NOT persisted across restarts. per-process, and deliberately NOT persisted across restarts.
reading.py neutral long-form reading helpers (stdlib): the
`bookmarks.json` beside the saved books (load/save/read a book
key -> last read offset, atomic write) and a deterministic
speakable chunker (`chunk_text` -> `(offset, chunk)` at
paragraph/sentence boundaries). Knows nothing about the
scheduler, a gateway, or audio.
speech.py the scheduler's speech channel (SpeechService on
ActionContext.speech, the sibling of timers): a skill that
resolves a long text to be read aloud registers a `ReadAloud`
(path + bookmark key + start offset) and returns immediately;
the gateway owning the chat drains it and hands it to the
platform adapter, which streams it with text-to-speech until
the user stops it. Neutral and stdlib-only; the skill never
reaches into a front end.
engine.py DecisionEngine (the pluggable contract: call/warm/loaded/ engine.py DecisionEngine (the pluggable contract: call/warm/loaded/
generate) + SemIfEngine, the default local provider -> generate) + SemIfEngine, the default local provider ->
semif_phase1.llamacpp_backend (lazy import); call() scores a semif_phase1.llamacpp_backend (lazy import); call() scores a
@@ -213,6 +227,16 @@ winnow.py WinnowEngine -> a remote Winnow `/v1/systemone` typed-decision
ids, and generate() via /v1/chat/completions. stdlib urllib; an ids, and generate() via /v1/chat/completions. stdlib urllib; an
internal lock serializes on the single-slot server; every internal lock serializes on the single-slot server; every
failure raises EngineUnavailable (fatal, like the local engine) failure raises EngineUnavailable (fatal, like the local engine)
ollama_systemone.py
OllamaSystemOneEngine -> ollama's native System One
`/v1/systemone` route (`engine.provider == "ollama"`): same
DecisionRequest -> choice mapping and strict distribution
validation, plus ollama's own edges — reachability/warmth via
/api/version + /api/show (model exists, `decision` capability,
real `num_ctx`), request `keep_alive`, `string | null` criteria
descriptions, and no text generation (decision models don't
generate). stdlib urllib; internal lock; every failure raises
EngineUnavailable.
codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill
bodies against CODEGEN.md (real actions via stdlib transports, bodies against CODEGEN.md (real actions via stdlib transports,
data from the runner via ctx.config, never embedded; bodies data from the runner via ctx.config, never embedded; bodies
@@ -353,8 +377,9 @@ 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
(webrtcvad, energy fallback), speech-to-text (faster-whisper) (webrtcvad, energy fallback), speech-to-text (faster-whisper)
and text-to-speech (Piper) over `sounddevice`; half-duplex and text-to-speech (Piper) over `sounddevice`; half-duplex by
(capture discarded while speaking). Every heavy dep is default with optional wake-word barge-in (abort a spoken reply
and listen for an interrupt command). Every heavy dep is
lazy-imported, keeping the module stdlib-only; the engine lazy-imported, keeping the module stdlib-only; the engine
interfaces are plain classes so tests inject fakes. Knows interfaces are plain classes so tests inject fakes. Knows
nothing about the scheduler or the gateway. nothing about the scheduler or the gateway.
@@ -705,11 +730,19 @@ CLI, unit tests (24) + integration tests (2).
single-session routing, `needs_input` questions, repairs, and approvals all single-session routing, `needs_input` questions, repairs, and approvals all
work through `GatewayService` unchanged — a spoken command is just text from work through `GatewayService` unchanged — a spoken command is just text from
`voice:<chat_id>`, and every reply is spoken. No remote peer and no allowlist `voice:<chat_id>`, and every reply is spoken. No remote peer and no allowlist
(physical mic access is the authorization). Half-duplex: capture is discarded (physical mic access is the authorization). The wake word is required before
while a reply is speaking (no barge-in yet); the wake word is required before
every command and is held while the scheduler's single slot is still running every command and is held while the scheduler's single slot is still running
the current request (`GatewayService.input_ready`), so a second command cannot the current request (`GatewayService.input_ready`), so a second command cannot
start until the first reaches a result (or pauses for the user's answer). The start until the first reaches a result (or pauses for the user's answer).
**Barge-in** (`gateway.voice.barge_in.enabled`, default on): while a reply is
speaking the wake word is still scored, so the user can interrupt — the
playback is aborted (chunked streaming with a `stop_event`; the reply is muted
until the interrupt is handled so it never resumes over the user) and the
following command is captured. A bare "stop"/"cancel" (or a short variant)
aborts the spoken reply and drops anything queued behind it; anything else is
run as a new command. `barge_in.threshold` raises the wake bar for barge-in
only (0 = use `wake.threshold`) so the agent's own TTS cannot self-trigger.
Disable for strict half-duplex. The
whole voice stack is optional and lazy-imported (`requirements/voice.txt`, whole voice stack is optional and lazy-imported (`requirements/voice.txt`,
pinned separately from the engine set since it is hardware-dependent); the pinned separately from the engine set since it is hardware-dependent); the
gateway refuses to start with an install hint. `bootstrap.sh --voice` gateway refuses to start with an install hint. `bootstrap.sh --voice`
@@ -717,6 +750,40 @@ CLI, unit tests (24) + integration tests (2).
the venv under `.runtime/venv`, the Piper voice under `.runtime/voice/tts`, the venv under `.runtime/venv`, the Piper voice under `.runtime/voice/tts`,
the faster-whisper model in the `.runtime/hf` cache). See the faster-whisper model in the `.runtime/hf` cache). See
"### gateway (messenger intake)". "### gateway (messenger intake)".
- **Read a book aloud over a voice front end** (Oct 2026): a skill that
resolves a long text can ask the front end to read it aloud instead of
returning a bounded summary. The skill asks the scheduler's speech channel
(`ctx.speech`, `semif_agent/speech.py` — the sibling of `ctx.timers`)
`supports(source)`; the gateway service registers the per-source predicate at
startup, so a skill only offers a read to a front end that can stream one
(a typed request, or a platform with no voice path, keeps the saved-file
summary). It then registers a `ReadAloud` and returns immediately;
`GatewayService.surface()` drains it and queues an `OutboundMessage` whose
`stream` field carries the request to the platform that owns the run (any
other platform is traced `gateway_stream_unsupported` and skipped, never
handed a message it would drop silently). Two adapters stream it: the local
**voice gateway** plays it through the daemon's Piper voice one chunk at a
time (`gateway.voice.read.enabled`), and the **LXMF voice gateway** sends it
to a voice chat as a sequence of Piper Opus/OGG voice messages
(`gateway.lxmf.voice.read.enabled`; a chat that last messaged by voice). Both
use `reading.chunk_text` with a chunk size clamped below the platform's
speakable budget so a chunk is never truncated, and write the bookmark before
each chunk so the position is the interrupted chunk's start. The read is
**background**: it does not hold the scheduler's single slot, so the agent
stays free. A run that registers a read is treated as **terminal**
(`read_aloud_terminal`): the read is the answer, so `assess:outcome` must not
re-dispatch the request (which otherwise authored a spurious skill). The user
stops it like any spoken reply — a wake-word barge-in "stop", or on LXMF a
"stop" message (any new command also interrupts it; traced
`gateway_read_stop`/`_interrupted`/`_done` on voice,
`lxmf_read_*` on LXMF). Position lives in a `bookmarks.json` beside the saved
books (`semif_agent/reading.py`), so a later request resumes where the
listener stopped. `gutendex.read_book` is the first consumer: it checks the
**local library** (the books folder) first — a book already saved is read from
disk (matched by id, or by the name in the request) with no network, and a
catalog-resolved book is reused from disk rather than re-downloaded — then
over a voice front end reads it aloud, while over any other source it keeps
returning the saved-file summary.
- **Custom Piper voice (train your own)** (Oct 2026): the TTS voice is - **Custom Piper voice (train your own)** (Oct 2026): the TTS voice is
replaceable with one fine-tuned on the user's own recordings. This is an replaceable with one fine-tuned on the user's own recordings. This is an
optional, off-bootstrap pipeline (`scripts/voice-record.py` records an optional, off-bootstrap pipeline (`scripts/voice-record.py` records an
@@ -766,28 +833,45 @@ CLI, unit tests (24) + integration tests (2).
in config.json — the same provider pattern as `llm`/`codegen`. `"semif"` in config.json — the same provider pattern as `llm`/`codegen`. `"semif"`
(default) is the local llama.cpp GGUF (`SemIfEngine`); `"winnow"` is a remote (default) is the local llama.cpp GGUF (`SemIfEngine`); `"winnow"` is a remote
Winnow `/v1/systemone` typed-decision API (`semif_agent.winnow.WinnowEngine`, Winnow `/v1/systemone` typed-decision API (`semif_agent.winnow.WinnowEngine`,
configured by the nested `engine.winnow` block). `cli.build_engine` picks the configured by the nested `engine.winnow` block); `"ollama"` is ollama's native
class; `SemIfEngine`/`WinnowEngine` both satisfy `engine.DecisionEngine` System One `/v1/systemone` route
(`call`/`warm`/`loaded`/`generate`). (`semif_agent.ollama_systemone.OllamaSystemOneEngine`, configured by the
nested `engine.ollama` block). `cli.build_engine` picks the class;
`SemIfEngine`/`WinnowEngine`/`OllamaSystemOneEngine` all satisfy
`engine.DecisionEngine` (`call`/`warm`/`loaded`/`generate`).
- **`winnow` and `ollama` are different edges of the same System One contract.**
Both map the flat decision onto a `choice` question and validate/normalize the
returned distribution over exactly the requested option ids, but the
`ollama` provider implements the deployment details only ollama has: there is
no `/health`, so `warm()` probes `GET /api/version` and `POST /api/show`
(which also proves the model is pulled and advertises the `decision`
capability), `engine.ollama.context_tokens: 0` follows the model's real
`num_ctx` from `/api/show`, `keep_alive` rides on the request, choice criteria
descriptions use the ollama subset `string | null`, and a choice question
needs at least two options. Decision models do not generate text, so
`OllamaSystemOneEngine.generate` raises `EngineUnavailable` — use
`llm.provider == "ollama"` for the chat path.
- **The engine is always real and every `EngineUnavailable` is fatal**, - **The engine is always real and every `EngineUnavailable` is fatal**,
whichever provider is selected: `WinnowEngine` converts every network, HTTP, whichever provider is selected: `WinnowEngine`/`OllamaSystemOneEngine` convert
and malformed/unnormalized-distribution failure into `EngineUnavailable` so every network, HTTP, and malformed/unnormalized-distribution failure into
the scheduler's fatal path (and the codegen watchdog / LLM bridge's graceful `EngineUnavailable` so the scheduler's fatal path (and the codegen watchdog /
paths) behave identically to the local engine. There is no fallback model. LLM bridge's graceful paths) behave identically to the local engine. There is
no fallback model.
- The agent's flat decision (`state` + `question` + typed `options`) maps onto - The agent's flat decision (`state` + `question` + typed `options`) maps onto
Winnow's `choice` question type (`options` -> `criteria` id->description, the System One `choice` question type (`options` -> `criteria`
`question` -> `instructions`); the returned distribution is validated against id->description, `question` -> `instructions`); the returned distribution is
exactly the requested option ids and normalized. `generate` goes through the validated against exactly the requested option ids and normalized. For
same server's `/v1/chat/completions`, so `llm.provider == "semif"` keeps `winnow`, `generate` goes through the same server's `/v1/chat/completions`, so
working when the decision engine is Winnow. `llm.provider == "semif"` keeps working when the decision engine is Winnow.
- Swapping the decision model changes routing/assessment behaviour and the - Swapping the decision model changes routing/assessment behaviour and the
decision-log distribution; that is the intended per-machine choice. The decision-log distribution; that is the intended per-machine choice. The
decision log and `dream` cost are unchanged because `DecisionResult` is the decision log and `dream` cost are unchanged because `DecisionResult` is the
same contract. same contract.
- Context differs by provider (the local engine's `engine.context_tokens` vs the - Context differs by provider (the local engine's `engine.context_tokens` vs the
remote server's own `--ctx-size`, mirrored in `engine.winnow.context_tokens`); remote server's own decision window, mirrored in `engine.winnow.context_tokens`
a state that overflows is a fatal `EngineUnavailable`, the same class as the or discovered from `engine.ollama`'s `/api/show` `num_ctx`); a state that
local token limit. Every engine exposes its window as `context_tokens` (a overflows is a fatal `EngineUnavailable`, the same class as the local token
limit. Every engine exposes its window as `context_tokens` (a
`DecisionEngine` property), which the scheduler uses to size generated `DecisionEngine` property), which the scheduler uses to size generated
artifacts — see "Artifact size budget". artifacts — see "Artifact size budget".
@@ -833,8 +917,8 @@ CLI, unit tests (24) + integration tests (2).
which installs the Vulkan build prereqs which installs the Vulkan build prereqs
(`libvulkan-dev glslc spirv-headers glslang-tools`) when needed. A CPU-only (`libvulkan-dev glslc spirv-headers glslang-tools`) when needed. A CPU-only
host keeps the default CPU wheel — a GPU build is slower on CPU. A host whose host keeps the default CPU wheel — a GPU build is slower on CPU. A host whose
`engine.provider` is `"winnow"` installs none of this (no clone, no GGUF, no `engine.provider` is `"winnow"` or `"ollama"` installs none of this (no clone,
tokenizer, no engine deps). no GGUF, no tokenizer, no engine deps).
- **Expected pip warnings:** pip reports "dependency conflicts" against - **Expected pip warnings:** pip reports "dependency conflicts" against
semif-phase1's declared requirements (torch/accelerate/protobuf/sentencepiece semif-phase1's declared requirements (torch/accelerate/protobuf/sentencepiece
not installed, numpy 2.2.6 vs 2.3.5). These are informational — the staging not installed, numpy 2.2.6 vs 2.3.5). These are informational — the staging
@@ -914,7 +998,8 @@ CLI, unit tests (24) + integration tests (2).
a checkout (register its SSH key on your git host first), then run a checkout (register its SSH key on your git host first), then run
`scripts/bootstrap.sh`. On a fresh machine it runs the **setup interview** `scripts/bootstrap.sh`. On a fresh machine it runs the **setup interview**
(`semif_agent/setup.py`, the `cli setup` subcommand) and writes the split (`semif_agent/setup.py`, the `cli setup` subcommand) and writes the split
config from the answers — decision engine (local SemIf 4B or remote Winnow), config from the answers — decision engine (local SemIf 4B, remote Winnow, or
an Ollama System One decision model),
new-skill authoring mode (+ `llm`/`codegen` endpoints when enabled), capability new-skill authoring mode (+ `llm`/`codegen` endpoints when enabled), capability
packs, gateways, and timezone — then installs only what those answers require packs, gateways, and timezone — then installs only what those answers require
(the install *plan* drives every conditional stage). Which packs exist is owned (the install *plan* drives every conditional stage). Which packs exist is owned
@@ -1468,6 +1553,14 @@ CLI, unit tests (24) + integration tests (2).
is stripped — so a reply (text or voice) is the answer, not the scheduler's is stripped — so a reply (text or voice) is the answer, not the scheduler's
internals. Questions, repair offers, approvals, and timer notifications still internals. Questions, repair offers, approvals, and timer notifications still
pass through. pass through.
**Read-aloud**: a `ReadAloud` the service routes here (a skill posted it via
`ctx.speech`) is streamed to the chat as a sequence of voice messages: `_stream`
reads the saved text, Piper-synthesizes each chunk to Opus/OGG, and queues it
on the daemon, writing the bookmark before each chunk. It stops when the text
ends or the user interrupts — a "stop" message (intercepted in `_deliver`,
never submitted as a request) or any new command. Only a chat that last
messaged by voice receives one (`speech_stream_ready`); a text chat keeps the
skill's saved-file summary. `gateway.lxmf.voice.read.{enabled,chunk_chars}`.
- **Voice adapter** (`gateway/voice.py`): the local microphone front end. It is - **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
@@ -1493,9 +1586,19 @@ CLI, unit tests (24) + integration tests (2).
phrase's tail, not the command — until `vad.min_command_ms` of speech is in phrase's tail, not the command — until `vad.min_command_ms` of speech is in
hand the trailing-silence endpoint uses `vad.initial_silence_ms`, so a natural hand the trailing-silence endpoint uses `vad.initial_silence_ms`, so a natural
pause before the command does not end the capture (then `vad.silence_ms`). pause before the command does not end the capture (then `vad.silence_ms`).
**Half-duplex**: capture frames are discarded while a **Half-duplex by default, barge-in optional** (`gateway.voice.barge_in`):
reply is speaking, so the agent never transcribes itself (no barge-in yet); capture frames are normally discarded while a reply is speaking, so the agent
the wake word is required before every command, and is **held while the never transcribes itself; with `barge_in.enabled` the wake word is still
scored during playback, so the user can interrupt. The daemon's `play` streams
the reply in small chunks and watches a `stop_event`, so a barge-in aborts the
playback promptly; the daemon then mutes speech (`_mute`), tells the front end
via `on_barge_in(True/False)`, and captures the following command.
`barge_in.threshold` (0 = `wake.threshold`) is a separate, usually higher wake
bar for barge-in so the agent's own TTS cannot self-trigger. The
`VoiceAdapter` tags that utterance (`raw["barge_in"]`): a bare "stop"/"cancel"
(`_is_stop_command`) drops any queued replies and unmutes without submitting,
while anything else is run as a new command and unmutes when handled. The wake
word is required before every command, and is **held while the
scheduler slot is busy** (`GatewayService.input_ready`): a wake that fires scheduler slot is busy** (`GatewayService.input_ready`): a wake that fires
while the current request is still running is ignored (traced while the current request is still running is ignored (traced
`voice_wake_blocked`), so a second command cannot start until the first `voice_wake_blocked`), so a second command cannot start until the first
@@ -1508,6 +1611,15 @@ CLI, unit tests (24) + integration tests (2).
is stripped — so the spoken output is the answer, not the scheduler's is stripped — so the spoken output is the answer, not the scheduler's
internals. Questions, repair offers, approvals, and timer notifications are internals. Questions, repair offers, approvals, and timer notifications are
still spoken. still spoken.
**Read-aloud**: the pump also handles an `OutboundMessage` whose `stream`
carries a `ReadAloud` (a skill posted it via `ctx.speech`; the service routes
it here — see the roadmap entry). `_stream` reads the saved text and speaks it
chunk by chunk through the daemon's Piper voice, writing the bookmark before
each chunk; it stops when the text ends, when the user stops it (a barge-in
"stop" — the daemon mutes playback, which the loop notices — or a bare "stop"
heard between chunks), or when any new command arrives. `supports_speech_stream`
(`gateway.voice.read.enabled`, default on) gates the whole path;
`read.chunk_chars` bounds one chunk (clamped below `max_speak_chars`).
Every heavy dep Every heavy dep
(`sounddevice`/`openwakeword`/`faster_whisper`/`piper`/`onnxruntime`) is (`sounddevice`/`openwakeword`/`faster_whisper`/`piper`/`onnxruntime`) is
**lazy-imported**; `check_requirements()` returns an install hint and the **lazy-imported**; `check_requirements()` returns an install hint and the
@@ -1621,7 +1733,8 @@ CLI, unit tests (24) + integration tests (2).
the Nextcloud/Outlook/Browser bridges over a loopback `http.server` with a fake the Nextcloud/Outlook/Browser bridges over a loopback `http.server` with a fake
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 and
barge-in — wake-abort, mute, stop/new-command classification,
`speak` truncation/failure, adapter + CLI wiring) plus the transcribe-only `speak` truncation/failure, adapter + CLI wiring) plus the transcribe-only
helpers (`check_codec2_requirements`, `decode_codec2` over an injected fake helpers (`check_codec2_requirements`, `decode_codec2` over an injected fake
`pycodec2`, `pcm_to_wav`) and the voice-reply helpers `pycodec2`, `pcm_to_wav`) and the voice-reply helpers
@@ -1690,7 +1803,8 @@ CLI, unit tests (24) + integration tests (2).
`packs.<name>`. Shared, skill-less bridges (the LLM bridge) live in `packs.<name>`. Shared, skill-less bridges (the LLM bridge) live in
`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), `gutendex` (Project Gutenberg book catalog + full-text download;
no bridge) and `essentials` (the built-in local utilities `time` +
`calculator` + `skills`; no bridge) — each in its own repository. Adding a `calculator` + `skills`; no bridge) — each in its own repository. Adding a
concern means adding a pack repo, not editing `skills.py`. concern means adding a pack repo, not editing `skills.py`.
+13 -6
View File
@@ -445,13 +445,18 @@ what it needs, based on the answers to a short first-run interview.
### Prerequisites: the decision engine, and optional models ### Prerequisites: the decision engine, and optional models
The **decision engine** routes every request. It runs one of two ways, chosen in The **decision engine** routes every request. It runs one of three ways,
the interview: chosen in the interview:
- **local** — the pinned SemIf 4B GGUF via llama.cpp (no network). This is the - **local** — the pinned SemIf 4B GGUF via llama.cpp (no network). This is the
default and the whole minimum path. default and the whole minimum path.
- **remote** — a Winnow `/v1/systemone` decision server (`engine.provider == - **remote** — a Winnow `/v1/systemone` decision server (`engine.provider ==
"winnow"`). The local engine clone, GGUF, and tokenizer are then skipped. "winnow"`). The local engine clone, GGUF, and tokenizer are then skipped.
- **remote Ollama** — ollama's native System One `/v1/systemone` route
(`engine.provider == "ollama"`) against a pulled decision model. It probes
ollama's `/api/version` + `/api/show`, follows the model's real `num_ctx`, and
skips the local engine clone/GGUF/tokenizer too. System One models do not
generate text, so this provider cannot back `llm.provider == "semif"`.
The local engine is CPU by default; to offload it to a GPU, set The local engine is CPU by default; to offload it to a GPU, set
`engine.gpu_layers` in `config.json` and run `engine.gpu_layers` in `config.json` and run
@@ -467,7 +472,8 @@ shipped packs. When it is on, two OpenAI-compatible endpoints are required
newly created category/skill. Its `provider` can be `"ollama"` (default), newly created category/skill. Its `provider` can be `"ollama"` (default),
`"opencode"` (the hosted Console API), or `"semif"` — the already-loaded `"opencode"` (the hosted Console API), or `"semif"` — the already-loaded
decision engine model generates in-process, with no endpoint and no decision engine model generates in-process, with no endpoint and no
`llm.model` at all. `llm.model` at all (the local SemIf or Winnow engine only; an Ollama
System One decision model does not generate text).
- **`codegen`** — a large, code-capable model that writes skill bodies. This is - **`codegen`** — a large, code-capable model that writes skill bodies. This is
slow and ideally on a beefier host. slow and ideally on a beefier host.
@@ -482,7 +488,8 @@ scripts/bootstrap.sh
On a fresh machine the script **asks a few questions** and writes this machine's On a fresh machine the script **asks a few questions** and writes this machine's
config from the answers: config from the answers:
1. **Decision engine** — local SemIf 4B, or a remote Winnow server (URL/model/key). 1. **Decision engine** — local SemIf 4B, a remote Winnow server, or a remote
Ollama System One decision model (URL/model/key).
2. **Skill authoring** — `deny` (default), `ask`, or `allow`; if enabled, the 2. **Skill authoring** — `deny` (default), `ask`, or `allow`; if enabled, the
`llm` + `codegen` endpoints and credentials. `llm` + `codegen` endpoints and credentials.
3. **Capabilities** — the skill packs to enable, offered from the pack index 3. **Capabilities** — the skill packs to enable, offered from the pack index
@@ -498,8 +505,8 @@ 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, skill listing). No account, no network, no gateway, no heavy calculator, skill listing). No account, no network, no gateway, no heavy
downloads. downloads.
- **maximum** — every pack, a remote Winnow engine, remote `llm`/`codegen` - **maximum** — every pack, a remote Winnow or Ollama System One decision
endpoints, and all gateways. engine, remote `llm`/`codegen` endpoints, and all gateways.
Non-interactive runs: `--yes` takes the minimum defaults; `--answers FILE` Non-interactive runs: `--yes` takes the minimum defaults; `--answers FILE`
replays a saved answer set (JSON matching the `setup` fields). The script is replays a saved answer set (JSON matching the `setup` fields). The script is
+25 -1
View File
@@ -39,6 +39,17 @@
"user_agent": "semif-agent", "user_agent": "semif-agent",
"extra_headers": {} "extra_headers": {}
}, },
"ollama": {
"base_url": "http://127.0.0.1:11434",
"model": "",
"context_tokens": 16384,
"api_key": "!secret engine_ollama_api_key",
"timeout": 120,
"retries": 0,
"keep_alive": "",
"user_agent": "semif-agent",
"extra_headers": {}
},
"gguf": "" "gguf": ""
}, },
"llm": { "llm": {
@@ -164,6 +175,10 @@
"reply_with_voice": true, "reply_with_voice": true,
"max_speak_chars": 600, "max_speak_chars": 600,
"reply_bitrate": 24000, "reply_bitrate": 24000,
"read": {
"enabled": true,
"chunk_chars": 300
},
"stt": { "stt": {
"model": "base.en", "model": "base.en",
"device": "cpu", "device": "cpu",
@@ -187,6 +202,10 @@
"reply_prefix": "", "reply_prefix": "",
"result_only": true, "result_only": true,
"max_speak_chars": 600, "max_speak_chars": 600,
"read": {
"enabled": true,
"chunk_chars": 300
},
"listen_timeout_s": 3.0, "listen_timeout_s": 3.0,
"cue": { "cue": {
"enabled": true, "enabled": true,
@@ -246,7 +265,12 @@
"aggressiveness": 2, "aggressiveness": 2,
"energy_threshold": 200.0 "energy_threshold": 200.0
}, },
"follow_up_window_s": 0.0 "follow_up_window_s": 0.0,
"barge_in": {
"enabled": true,
"wait_s": 2.0,
"threshold": 0.0
}
} }
}, },
"dashboard": { "dashboard": {
+28 -5
View File
@@ -41,6 +41,7 @@ from .console import (
) )
from .decisions import DecisionRequest, Option from .decisions import DecisionRequest, Option
from .engine import DecisionEngine, EngineConfig, EngineUnavailable, SemIfEngine from .engine import DecisionEngine, EngineConfig, EngineUnavailable, SemIfEngine
from .ollama_systemone import OllamaSystemOneConfig, OllamaSystemOneEngine
from .winnow import WinnowConfig, WinnowEngine from .winnow import WinnowConfig, WinnowEngine
from .llm import LLMClient, SemIfLLMClient from .llm import LLMClient, SemIfLLMClient
from .log import DecisionLog from .log import DecisionLog
@@ -54,6 +55,7 @@ from .trace import TraceLog
REPO_ROOT = Path(__file__).resolve().parent.parent REPO_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_WINNOW_URL = "http://127.0.0.1:8091" DEFAULT_WINNOW_URL = "http://127.0.0.1:8091"
DEFAULT_OLLAMA_SYSTEMONE_URL = "http://127.0.0.1:11434"
_PATH_KEYS = ( _PATH_KEYS = (
"skill_packs", "skill_packs",
@@ -221,14 +223,19 @@ def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
* ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`), built * ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`), built
from the per-machine `engine` knobs + the pinned refs in pins.json. from the per-machine `engine` knobs + the pinned refs in pins.json.
* ``"winnow"`` — a remote `/v1/systemone` typed-decision API * ``"winnow"`` — a remote Winnow `/v1/systemone` typed-decision API
(`WinnowEngine`), configured by the nested `engine.winnow` block (`WinnowEngine`), configured by the nested `engine.winnow` block
(`base_url`/`model`/`api_key`/`timeout`/`retries`). (`base_url`/`model`/`api_key`/`timeout`/`retries`).
* ``"ollama"`` — ollama's native System One `/v1/systemone` route
(`OllamaSystemOneEngine`), configured by the nested `engine.ollama` block
(`base_url`/`model`/`keep_alive`/`api_key`/`timeout`/`retries`), probed
through ollama's own `/api/version` + `/api/show` endpoints.
The engine is always real: a provider that cannot be reached raises The engine is always real: a provider that cannot be reached raises
`EngineUnavailable` at call time, which the scheduler treats as fatal. The `EngineUnavailable` at call time, which the scheduler treats as fatal. The
`winnow` model is required (no default) exactly as `llm.model`/`codegen.model` `winnow` and `ollama` models are required (no default) exactly as
are, so a misconfigured endpoint fails as an actionable config error. `llm.model`/`codegen.model` are, so a misconfigured endpoint fails as an
actionable config error.
""" """
eng = config.get("engine", {}) or {} eng = config.get("engine", {}) or {}
provider = str(eng.get("provider", "semif") or "semif").lower() provider = str(eng.get("provider", "semif") or "semif").lower()
@@ -247,6 +254,22 @@ def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
user_agent=str(win.get("user_agent") or "semif-agent"), user_agent=str(win.get("user_agent") or "semif-agent"),
) )
) )
if provider == "ollama":
block = eng.get("ollama", {}) or {}
endpoint = _provider_endpoint(block, DEFAULT_OLLAMA_SYSTEMONE_URL)
return OllamaSystemOneEngine(
OllamaSystemOneConfig(
base_url=endpoint["base_url"],
model=_required_model(block, "engine.ollama"),
context_tokens=int(block.get("context_tokens", 16384)),
timeout=float(block.get("timeout", 120.0)),
retries=int(block.get("retries", 0)),
api_key=endpoint["api_key"],
extra_headers=endpoint["extra_headers"],
user_agent=str(block.get("user_agent") or "semif-agent"),
keep_alive=str(block.get("keep_alive") or ""),
)
)
return SemIfEngine(build_engine_config(config, pins)) return SemIfEngine(build_engine_config(config, pins))
@@ -1164,8 +1187,8 @@ def main(argv: list[str] | None = None) -> int:
formatter_class=argparse.RawDescriptionHelpFormatter, formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=( epilog=(
"answers JSON fields (all optional; --answers FILE):\n" "answers JSON fields (all optional; --answers FILE):\n"
" engine_provider (semif|winnow), winnow_base_url, winnow_model,\n" " engine_provider (semif|winnow|ollama), winnow_base_url, winnow_model,\n"
" winnow_api_key\n" " winnow_api_key, ollama_base_url, ollama_model, ollama_api_key\n"
" new_skill_creation (deny|ask|allow)\n" " new_skill_creation (deny|ask|allow)\n"
" llm_provider (semif|ollama|opencode|openai), llm_base_url,\n" " llm_provider (semif|ollama|opencode|openai), llm_base_url,\n"
" llm_model, llm_api_key\n" " llm_model, llm_api_key\n"
+32 -1
View File
@@ -75,6 +75,15 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': '
'retries': {'default': 0, 'type': 'int'}, 'retries': {'default': 0, 'type': 'int'},
'user_agent': {'default': 'semif-agent', 'type': 'str'}, 'user_agent': {'default': 'semif-agent', 'type': 'str'},
'extra_headers': {'default': {}, 'type': 'dict'}}, 'extra_headers': {'default': {}, 'type': 'dict'}},
'ollama': {'base_url': {'default': 'http://127.0.0.1:11434', 'type': 'str'},
'model': {'default': '', 'type': 'str'},
'context_tokens': {'default': 16384, 'type': 'int'},
'api_key': {'default': '', 'type': 'str', 'secret': True},
'timeout': {'default': 120, 'type': 'int'},
'retries': {'default': 0, 'type': 'int'},
'keep_alive': {'default': '', 'type': 'str'},
'user_agent': {'default': 'semif-agent', 'type': 'str'},
'extra_headers': {'default': {}, 'type': 'dict'}},
'gguf': {'default': '', 'type': 'str'}}, 'gguf': {'default': '', 'type': 'str'}},
'llm': {'provider': {'default': 'ollama', 'type': 'str'}, 'llm': {'provider': {'default': 'ollama', 'type': 'str'},
'base_url': {'default': 'http://localhost:11434/v1', 'type': 'str'}, 'base_url': {'default': 'http://localhost:11434/v1', 'type': 'str'},
@@ -180,6 +189,12 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': '
'reply_with_voice': {'default': True, 'type': 'bool'}, 'reply_with_voice': {'default': True, 'type': 'bool'},
'max_speak_chars': {'default': 600, 'type': 'int'}, 'max_speak_chars': {'default': 600, 'type': 'int'},
'reply_bitrate': {'default': 24000, 'type': 'int'}, 'reply_bitrate': {'default': 24000, 'type': 'int'},
# Read a long text (a book) aloud to a voice
# chat as a sequence of voice messages until the
# user sends "stop". Position is kept in a
# bookmarks.json beside the saved text.
'read': {'enabled': {'default': True, 'type': 'bool'},
'chunk_chars': {'default': 300, 'type': 'int'}},
'stt': {'model': {'default': 'base.en', 'type': 'str'}, 'stt': {'model': {'default': 'base.en', 'type': 'str'},
'device': {'default': 'cpu', 'type': 'str'}, 'device': {'default': 'cpu', 'type': 'str'},
'compute_type': {'default': 'int8', 'type': 'str'}, 'compute_type': {'default': 'int8', 'type': 'str'},
@@ -198,6 +213,13 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': '
'reply_prefix': {'default': '', 'type': 'str'}, 'reply_prefix': {'default': '', 'type': 'str'},
'result_only': {'default': True, 'type': 'bool'}, 'result_only': {'default': True, 'type': 'bool'},
'max_speak_chars': {'default': 600, 'type': 'int'}, 'max_speak_chars': {'default': 600, 'type': 'int'},
# Read a long text (a book) aloud: a skill registers a
# read-aloud request and this front end streams it through
# Piper one chunk at a time until the user stops it. The
# position is kept in a bookmarks.json beside the text.
# `chunk_chars` bounds one spoken chunk.
'read': {'enabled': {'default': True, 'type': 'bool'},
'chunk_chars': {'default': 300, 'type': 'int'}},
'listen_timeout_s': {'default': 3.0, 'type': 'float'}, 'listen_timeout_s': {'default': 3.0, 'type': 'float'},
'cue': {'enabled': {'default': True, 'type': 'bool'}, 'cue': {'enabled': {'default': True, 'type': 'bool'},
'frequency': {'default': 880, 'type': 'int'}, 'frequency': {'default': 880, 'type': 'int'},
@@ -237,7 +259,16 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': '
'initial_silence_ms': {'default': 1500, 'type': 'int'}, 'initial_silence_ms': {'default': 1500, 'type': 'int'},
'aggressiveness': {'default': 2, 'type': 'int'}, 'aggressiveness': {'default': 2, 'type': 'int'},
'energy_threshold': {'default': 200.0, 'type': 'float'}}, 'energy_threshold': {'default': 200.0, 'type': 'float'}},
'follow_up_window_s': {'default': 0.0, 'type': 'float'}}}, 'follow_up_window_s': {'default': 0.0, 'type': 'float'},
# Interrupt a spoken reply with the wake word: stop the
# playback, listen for a command, and either abort (a
# bare "stop"/"cancel") or run the new command. Disable
# for strict half-duplex (the agent never listens while
# speaking). `wait_s` bounds how long to wait for the
# interrupted playback to release the audio device.
'barge_in': {'enabled': {'default': True, 'type': 'bool'},
'wait_s': {'default': 2.0, 'type': 'float'},
'threshold': {'default': 0.0, 'type': 'float'}}}},
'dashboard': {'port': {'default': 8765, 'type': 'int'}, 'dashboard': {'port': {'default': 8765, 'type': 'int'},
'host': {'default': '127.0.0.1', 'type': 'str'}}, 'host': {'default': '127.0.0.1', 'type': 'str'}},
'skill_packs': {'default': 'packs', 'skill_packs': {'default': 'packs',
+7 -2
View File
@@ -9,7 +9,9 @@ installed. The shipped llama.cpp backend scores a local GGUF; it runs on CPU by
default, and `EngineConfig.gpu_layers` offloads to a GPU when llama-cpp-python default, and `EngineConfig.gpu_layers` offloads to a GPU when llama-cpp-python
was built with a GPU backend (Vulkan/ROCm/CUDA). This engine is only usable on a was built with a GPU backend (Vulkan/ROCm/CUDA). This engine is only usable on a
machine with SemIf and the pinned GGUF available; elsewhere calls raise machine with SemIf and the pinned GGUF available; elsewhere calls raise
EngineUnavailable. The remote alternative lives in `semif_agent.winnow`. EngineUnavailable. The remote alternatives live in `semif_agent.winnow` (the
Winnow reference server) and `semif_agent.ollama_systemone` (ollama's native
System One route).
""" """
from __future__ import annotations from __future__ import annotations
@@ -40,8 +42,11 @@ class DecisionEngine(ABC):
`llm.provider` / `codegen.provider`: `llm.provider` / `codegen.provider`:
* ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`). * ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`).
* ``"winnow"`` — a remote ``/v1/systemone`` typed-decision API * ``"winnow"`` — a remote Winnow ``/v1/systemone`` typed-decision API
(`semif_agent.winnow.WinnowEngine`). (`semif_agent.winnow.WinnowEngine`).
* ``"ollama"`` — ollama's native System One ``/v1/systemone`` route
(`semif_agent.ollama_systemone.OllamaSystemOneEngine`), probed through
ollama's own ``/api/version`` + ``/api/show`` endpoints.
The engine is always real: any failure to produce a decision raises The engine is always real: any failure to produce a decision raises
`EngineUnavailable`, which the scheduler treats as fatal. `generate` is the `EngineUnavailable`, which the scheduler treats as fatal. `generate` is the
+59 -1
View File
@@ -35,16 +35,74 @@ class InboundMessage:
@dataclass @dataclass
class OutboundMessage: class OutboundMessage:
"""One reply destined for an external chat.""" """One reply destined for an external chat.
`text` is the reply. `stream` optionally carries a long-form read-aloud
request (a `semif_agent.speech.ReadAloud`) instead of a plain line: the
voice front end streams it chunk-by-chunk with text-to-speech until the user
stops it. A platform that does not stream leaves it None and speaks `text`.
"""
chat_id: str chat_id: str
text: str text: str
stream: Any = None
#: Callback the adapter invokes for each authorized inbound message. #: Callback the adapter invokes for each authorized inbound message.
InboundHandler = Callable[[InboundMessage], None] InboundHandler = Callable[[InboundMessage], None]
#: Words/phrases that abort a long-form read-aloud (and a spoken reply) when
#: heard/typed. The match is on the whole normalized utterance (so "stop the
#: timer" stays a real command) with a first-word fallback only for a short
#: utterance with trailing filler ("stop please", "cancel that"). Shared by the
#: voice and LXMF adapters, which both stream read-aloud text.
_STOP_PHRASES = {
"stop",
"stop it",
"stop talking",
"stop please",
"cancel",
"cancel that",
"cancel please",
"quiet",
"quiet down",
"be quiet",
"silence",
"hush",
"shut up",
"never mind",
"nevermind",
"enough",
}
_STOP_FIRST_WORDS = {"stop", "cancel", "quiet", "silence", "hush", "shut", "enough"}
_STOP_FILLER = {"please", "now", "it", "that", "talking", "down", "up", "already"}
#: Characters stripped from a spoken utterance's edges before matching.
_STOP_PUNCT = " \t\r\n.,!?;:\"'()[]{}"
def is_stop_command(text: str) -> bool:
"""Whether an utterance means "stop talking" (vs a new command).
Deterministic vocabulary, no model: a bare "stop"/"cancel" (or a short
variant like "stop please") aborts a spoken reply / long-form read. Anything
longer is a real command and is submitted as a new request.
"""
cleaned = (text or "").strip().lower().strip(_STOP_PUNCT)
if not cleaned:
return False
if cleaned in _STOP_PHRASES:
return True
words = cleaned.split()
if len(words) > 3:
return False
first = words[0].strip(_STOP_PUNCT)
if first not in _STOP_FIRST_WORDS:
return False
return all(word.strip(_STOP_PUNCT) in _STOP_FILLER for word in words[1:])
class GatewayAdapter(ABC): class GatewayAdapter(ABC):
"""Transport contract for a messenger platform.""" """Transport contract for a messenger platform."""
+145 -1
View File
@@ -44,8 +44,10 @@ from __future__ import annotations
import os import os
import queue import queue
import threading import threading
import time
from semif_agent.lxmf_transport import LxmfDaemon from semif_agent.lxmf_transport import LxmfDaemon
from semif_agent.reading import DEFAULT_CHUNK_CHARS, chunk_text, save_bookmark
from semif_agent.voice_transport import ( from semif_agent.voice_transport import (
OPUS_OGG_BITRATE, OPUS_OGG_BITRATE,
build_synthesizer, build_synthesizer,
@@ -58,7 +60,7 @@ from semif_agent.voice_transport import (
pcm_to_wav, pcm_to_wav,
) )
from .base import GatewayAdapter, InboundMessage, OutboundMessage from .base import GatewayAdapter, InboundMessage, OutboundMessage, is_stop_command
#: Sent (once) when a voice message can't be transcribed at all. A spoken or #: 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. #: typed command still works, so the user is not left guessing.
@@ -141,6 +143,38 @@ class LxmfAdapter(GatewayAdapter):
self._timers: dict[str, threading.Timer] = {} self._timers: dict[str, threading.Timer] = {}
self._lock = threading.Lock() self._lock = threading.Lock()
self._on_inbound = None self._on_inbound = None
#: Read-aloud: a book is streamed to a voice chat as a sequence of
#: voice messages, one Piper-synthesized chunk each, until the user
#: sends "stop" or a new command. Only a voice chat can receive it, so
#: a text chat keeps the skill's saved-file summary.
read_cfg = self.voice_cfg.get("read", {}) or {}
self._read_enabled = bool(read_cfg.get("enabled", True))
self._read_chunk_chars = max(
1, int(read_cfg.get("chunk_chars", DEFAULT_CHUNK_CHARS) or DEFAULT_CHUNK_CHARS)
)
#: How many messages may be queued on the daemon ahead of the stream
#: (backpressure so a stop is prompt).
self._read_max_lead = max(1, int(read_cfg.get("max_lead", 4) or 4))
self._read_lock = threading.Lock()
self._read_stop = threading.Event()
self._read_key: str | None = None
self._read_chat: str | None = None
@property
def supports_speech_stream(self) -> bool:
"""Whether this adapter can deliver a read-aloud at all.
Only when voice replies are on: a read-aloud is sent as voice messages.
Whether a *particular* chat can receive one is `speech_stream_ready`.
"""
return bool(self.voice_enabled and self.reply_with_voice and self._read_enabled)
def speech_stream_ready(self, chat: str) -> bool:
"""Whether `chat` should get a read-aloud (it last messaged by voice)."""
if not self.supports_speech_stream:
return False
with self._lock:
return str(chat) in self._voice_chats
# ---- requirements ---- # ---- requirements ----
@@ -182,6 +216,15 @@ class LxmfAdapter(GatewayAdapter):
if message is None: if message is None:
self.daemon.enqueue(None) self.daemon.enqueue(None)
return return
if message.stream is not None:
try:
self._stream(message.stream)
except Exception as exc:
# A read failure must never kill the outbound pump.
self.daemon._event(
"lxmf_read_failed", message=str(exc)[:300]
)
continue
audio = self._voice_reply(message) audio = self._voice_reply(message)
self.daemon.enqueue(message.chat_id, message.text, audio=audio) self.daemon.enqueue(message.chat_id, message.text, audio=audio)
@@ -252,6 +295,14 @@ class LxmfAdapter(GatewayAdapter):
"""Hand one command to the service (never called on the router thread).""" """Hand one command to the service (never called on the router thread)."""
source_hash = str(message.get("source_hash") or "") source_hash = str(message.get("source_hash") or "")
display_name = message.get("display_name") display_name = message.get("display_name")
# Any command interrupts a read-aloud playing to this chat; a bare
# "stop"/"cancel" is not submitted as a request.
if self._stop_read_for_command(source_hash):
self.daemon._event(
"lxmf_read_stopped", contact_id=source_hash, chars=len(text)
)
if is_stop_command(text):
return
self.daemon._event( self.daemon._event(
"gateway_message", "gateway_message",
contact_id=source_hash, contact_id=source_hash,
@@ -488,3 +539,96 @@ class LxmfAdapter(GatewayAdapter):
self.daemon._event("lxmf_voice_tts_unavailable", message=str(exc)[:300]) self.daemon._event("lxmf_voice_tts_unavailable", message=str(exc)[:300])
return None return None
return self._synthesizer return self._synthesizer
# ---- read-aloud (a book streamed as voice messages) ----
def _stop_read_for_command(self, chat: str) -> bool:
"""Stop a read-aloud playing to `chat`; report whether one was active."""
with self._read_lock:
if self._read_key is None or self._read_chat != str(chat):
return False
self._read_stop.set()
return True
def _synthesize_chunk(self, text: str) -> bytes | None:
"""Piper-synthesize one chunk to Opus/OGG, or None (send it as text)."""
synthesizer = self._ensure_synthesizer()
if synthesizer is None:
return None
try:
pcm, sample_rate = synthesizer.synthesize(text)
except Exception as exc:
self.daemon._event("lxmf_voice_synth_failed", message=str(exc)[:300])
return None
if not pcm:
return None
audio = pcm_to_opus_ogg(pcm, sample_rate, self.voice_bitrate)
if not audio:
self.daemon._event("lxmf_voice_encode_failed", chars=len(text))
return None
return audio
def _stream(self, read) -> None:
"""Stream a read-aloud request as a sequence of voice messages.
Runs on the outbound pump thread: each chunk is synthesized and queued
to the daemon, and the bookmark is written before it is sent so a stop
leaves the position at the interrupted chunk. The read ends when the
text is finished or the user interrupts (a stop flag set by `_deliver`).
"""
chat = str(read.source or "").split(":", 1)[-1]
with self._read_lock:
self._read_stop.set() # supersede any prior read
stop = threading.Event()
self._read_stop = stop
self._read_key = read.key
self._read_chat = chat
try:
if not chat or not self.speech_stream_ready(chat):
return
try:
with open(read.path, "r", encoding="utf-8", errors="replace") as handle:
text = handle.read()
except OSError as exc:
self.daemon._event(
"lxmf_read_failed", contact_id=chat, message=str(exc)[:200]
)
return
chunk_chars = min(
self._read_chunk_chars,
max(1, int(read.chunk_chars or self._read_chunk_chars)),
)
if self.voice_max_chars > 0:
chunk_chars = min(chunk_chars, self.voice_max_chars)
self.daemon._event(
"lxmf_read_start",
contact_id=chat,
key=read.key,
start=read.start,
chars=len(text),
)
sent = 0
for offset, chunk in chunk_text(text, read.start, chunk_chars):
# Keep only a few messages queued ahead so a stop takes effect
# promptly instead of after a large backlog drains.
while not stop.is_set() and self.daemon.pending_sends() >= self._read_max_lead:
time.sleep(0.05)
if stop.is_set():
break
save_bookmark(read.bookmarks_path, read.key, offset, read.title)
self.daemon.enqueue(chat, chunk, audio=self._synthesize_chunk(chunk))
sent += 1
if stop.is_set():
self.daemon._event(
"lxmf_read_interrupted", contact_id=chat, key=read.key, chunks=sent
)
else:
save_bookmark(read.bookmarks_path, read.key, len(text), read.title)
self.daemon._event(
"lxmf_read_done", contact_id=chat, key=read.key, chunks=sent
)
finally:
with self._read_lock:
if self._read_stop is stop:
self._read_key = None
self._read_chat = None
+66
View File
@@ -179,6 +179,13 @@ class GatewayService:
setter = getattr(adapter, "set_input_ready", None) setter = getattr(adapter, "set_input_ready", None)
if callable(setter): if callable(setter):
setter(self.input_ready) setter(self.input_ready)
#: Tell the scheduler's speech channel which sources this service can
#: stream a read-aloud to, so a skill asks before it posts one.
speech = getattr(self.scheduler, "speech", None)
if speech is not None:
setter = getattr(speech, "set_stream_check", None)
if callable(setter):
setter(self.stream_ready)
self._owners: dict[str, Target] = {} self._owners: dict[str, Target] = {}
self._parents: dict[str, str] = {} self._parents: dict[str, str] = {}
self._pending_owner: Target | None = None self._pending_owner: Target | None = None
@@ -342,6 +349,29 @@ class GatewayService:
return True return True
return getattr(scheduler, "current", None) is None return getattr(scheduler, "current", None) is None
def stream_ready(self, source: str) -> bool:
"""Whether this service can stream a read-aloud to `source`.
The owning platform's adapter decides: the voice gateway always can
(when `read.enabled`); the LXMF adapter only for a chat that last
messaged by voice (a text chat keeps the saved-file summary). A source
with no known owner is not streamed.
"""
target = self._owner_from_source(source)
if target is None:
return False
platform, chat = target
adapter = self.adapters.get(platform)
if adapter is None:
return False
check = getattr(adapter, "speech_stream_ready", None)
if callable(check):
try:
return bool(check(chat))
except Exception:
return False
return bool(getattr(adapter, "supports_speech_stream", False))
def handle_inbound(self, msg: InboundMessage, platform: str | None = None) -> None: def handle_inbound(self, msg: InboundMessage, platform: str | None = None) -> None:
"""Handle one authorized inbound command. Called by the adapter.""" """Handle one authorized inbound command. Called by the adapter."""
if platform is None: if platform is None:
@@ -519,6 +549,16 @@ class GatewayService:
if target: if target:
self._reply(*target, fired.message, kind="notice") self._reply(*target, fired.message, kind="notice")
# Long-form read-aloud requests a skill posted for a voice front end:
# route each to the platform that owns the run. Only a streaming adapter
# (the voice gateway) can deliver one; others are traced and skipped.
speech = getattr(self.scheduler, "speech", None)
if speech is not None:
for read in speech.drain():
target = self._resolve_target(read.run_id, origin)
if target:
self._enqueue_stream(target, read)
# ---- scheduler requeue hook (called under the scheduler lock) ---- # ---- scheduler requeue hook (called under the scheduler lock) ----
def on_request_requeued(self, parent_id: str, child_id: str) -> None: def on_request_requeued(self, parent_id: str, child_id: str) -> None:
@@ -593,3 +633,29 @@ class GatewayService:
return return
self._trace("gateway_reply_queued", reply_kind=kind, chars=len(text)) self._trace("gateway_reply_queued", reply_kind=kind, chars=len(text))
target_queue.put(OutboundMessage(chat_id=str(chat_id), text=text)) target_queue.put(OutboundMessage(chat_id=str(chat_id), text=text))
def _enqueue_stream(self, target: Target, read) -> None:
"""Queue a read-aloud stream for the platform that can stream it.
Only an adapter that declares `supports_speech_stream` (the voice
gateway) can speak a long-form stream; a platform that cannot is traced
and skipped rather than handed a message it would drop silently.
"""
platform, chat_id = target
adapter = self.adapters.get(platform)
if adapter is None or not getattr(adapter, "supports_speech_stream", False):
self._trace(
"gateway_stream_unsupported",
platform=platform,
key=getattr(read, "key", ""),
)
return
self._trace(
"gateway_stream_queued",
platform=platform,
key=getattr(read, "key", ""),
start=getattr(read, "start", 0),
)
self.outbound[platform].put(
OutboundMessage(chat_id=str(chat_id), text="", stream=read)
)
+189 -3
View File
@@ -23,9 +23,14 @@ from __future__ import annotations
import queue import queue
import threading import threading
from semif_agent.reading import DEFAULT_CHUNK_CHARS, chunk_text, save_bookmark
from semif_agent.voice_transport import VoiceDaemon from semif_agent.voice_transport import VoiceDaemon
from .base import GatewayAdapter, InboundMessage, OutboundMessage from .base import GatewayAdapter, InboundMessage, OutboundMessage, is_stop_command
#: The stop vocabulary lives in `gateway.base` (shared with the LXMF adapter,
#: which also streams read-aloud text). Kept under the old name for callers.
_is_stop_command = is_stop_command
class VoiceAdapter(GatewayAdapter): class VoiceAdapter(GatewayAdapter):
@@ -41,12 +46,35 @@ class VoiceAdapter(GatewayAdapter):
self.display_name = str(cfg.get("display_name") or self.chat_id) self.display_name = str(cfg.get("display_name") or self.chat_id)
#: `run()` blocks on the mic; this daemon owns capture/wake/STT/TTS. #: `run()` blocks on the mic; this daemon owns capture/wake/STT/TTS.
self.daemon = VoiceDaemon(cfg, trace=trace, name=self.name) self.daemon = VoiceDaemon(cfg, trace=trace, name=self.name)
#: Set by the daemon while a barge-in command is being captured, so the
#: transcribed utterance is classified as an interrupt.
self._barged_in = False
self.daemon.on_barge_in = self._on_barge_in
self._on_inbound = None self._on_inbound = None
#: Utterances are handed to a worker thread, not run on the audio #: Utterances are handed to a worker thread, not run on the audio
#: thread: the scheduler is synchronous and can block on the decision #: thread: the scheduler is synchronous and can block on the decision
#: engine, and a slow or failing task must neither stop the mic being #: engine, and a slow or failing task must neither stop the mic being
#: read nor kill the front end. `None` asks the worker to stop. #: read nor kill the front end. `None` asks the worker to stop.
self._inbound: "queue.Queue[InboundMessage | None]" = queue.Queue() self._inbound: "queue.Queue[InboundMessage | None]" = queue.Queue()
#: The outbound reply queue (set in `run`), so a "stop" can drop replies
#: that were already queued behind the interrupted one.
self._outbound: "queue.Queue[OutboundMessage | None] | None" = None
#: Long-form read-aloud: the adapter streams a saved text through the
#: daemon's Piper voice one chunk at a time, and any inbound command
#: interrupts it. `read.enabled` (default on) gates the whole path;
#: `read.chunk_chars` bounds one spoken chunk (clamped to the speakable
#: budget so a chunk is never truncated).
read_cfg = cfg.get("read", {}) or {}
self.supports_speech_stream = bool(read_cfg.get("enabled", True))
self._read_chunk_chars = max(
1, int(read_cfg.get("chunk_chars", DEFAULT_CHUNK_CHARS) or DEFAULT_CHUNK_CHARS)
)
self._read_lock = threading.Lock()
#: Set to ask the active read to stop; swapped per read so a stale read
#: never observes a new read's stop signal.
self._read_stop = threading.Event()
#: The bookmark key of the active read (None when nothing is being read).
self._read_key: str | None = None
# ---- requirements ---- # ---- requirements ----
@@ -71,15 +99,27 @@ class VoiceAdapter(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:
# Drain the service's replies onto the daemon's speaker. Speaking # Drain the service's replies onto the daemon's speaker. Speaking
# blocks (it plays audio), so this runs off the listening thread. # blocks (it plays audio), so this runs off the listening thread. A
# read-aloud stream blocks here for as long as the user listens.
while True: while True:
message = outbound.get() message = outbound.get()
if message is None: if message is None:
self.daemon.stop() self.daemon.stop()
return return
if message.stream is not None:
try:
self._stream(message.stream)
except Exception as exc:
# A read failure must never kill the outbound pump (and
# with it the front end).
self.daemon._event(
"gateway_read_failed", message=str(exc)[:300]
)
continue
self.daemon._event("gateway_reply_dequeued", chars=len(message.text)) self.daemon._event("gateway_reply_dequeued", chars=len(message.text))
self.daemon.speak(message.text) self.daemon.speak(message.text)
@@ -112,6 +152,38 @@ class VoiceAdapter(GatewayAdapter):
self._handle(message) self._handle(message)
def _handle(self, message: InboundMessage) -> None: def _handle(self, message: InboundMessage) -> None:
# Any inbound command interrupts an in-progress read-aloud: the user
# either said "stop" or wants to do something else. The bookmark already
# points at the chunk that was interrupted, so a later request resumes
# there.
was_reading = self._stop_read_for_command(message)
if message.raw.get("barge_in"):
if _is_stop_command(message.text):
# A "stop"/"cancel" after a barge-in aborts the spoken reply and
# is not a request: the daemon already cut the playback, and any
# reply still queued behind it is stale output the user stopped.
self.daemon._event("gateway_barge_in_stop", chars=len(message.text))
self._drop_pending_speech()
self.daemon.set_muted(False)
return
# A new command after a barge-in: the playback was already aborted,
# so just run it (and unmute once it has been handled).
self.daemon._event("gateway_barge_in_command", chars=len(message.text))
try:
if self._on_inbound is not None:
self._on_inbound(message)
except Exception as exc:
self.daemon._event("gateway_handler_failed", message=str(exc)[:300])
self.daemon.speak("Sorry, something went wrong handling that.")
finally:
self.daemon.set_muted(False)
return
if was_reading and _is_stop_command(message.text):
# A bare "stop" heard between chunks (not a barge-in) stops the
# reading and is not submitted as a request.
self.daemon._event("gateway_read_stopped", chars=len(message.text))
self._drop_pending_speech()
return
if self._on_inbound is None: if self._on_inbound is None:
return return
try: try:
@@ -120,10 +192,124 @@ class VoiceAdapter(GatewayAdapter):
self.daemon._event("gateway_handler_failed", message=str(exc)[:300]) self.daemon._event("gateway_handler_failed", message=str(exc)[:300])
self.daemon.speak("Sorry, something went wrong handling that.") self.daemon.speak("Sorry, something went wrong handling that.")
# ---- read-aloud (long-form streaming) ----
def _read_active(self) -> bool:
with self._read_lock:
return self._read_key is not None
def _stop_read_for_command(self, message: InboundMessage) -> bool:
"""Stop an active read when a command arrives; report whether one was."""
if not self._read_active():
return False
reason = "barge_in" if message.raw.get("barge_in") else "new_command"
self._stop_reading(reason)
return True
def _stop_reading(self, reason: str) -> None:
"""Ask the active read to stop at the next chunk boundary.
The bookmark was already written for the chunk being spoken, so the
position is correct without any extra bookkeeping here.
"""
with self._read_lock:
if self._read_key is None:
return
key = self._read_key
self._read_stop.set()
self.daemon._event("gateway_read_stop", key=key, reason=reason)
def _stream(self, read) -> None:
"""Stream a read-aloud request through the daemon's Piper voice.
Chunks are spoken one at a time; the bookmark is written before each
chunk so a stop (or a crash) leaves the position at the interrupted
chunk. The read ends when the text is finished or the user interrupts
(a stop flag set by `_handle`, or a barge-in muting playback).
"""
with self._read_lock:
self._read_stop.set() # supersede any prior read
stop = threading.Event()
self._read_stop = stop
self._read_key = read.key
try:
try:
with open(read.path, "r", encoding="utf-8", errors="replace") as handle:
text = handle.read()
except OSError as exc:
self.daemon._event(
"gateway_read_failed", key=read.key, message=str(exc)[:200]
)
return
chunk_chars = min(
self._read_chunk_chars,
max(1, int(read.chunk_chars or self._read_chunk_chars)),
)
# Never exceed the daemon's speakable budget, or a chunk would be
# truncated and text would be lost.
speak_limit = int(getattr(self.daemon, "max_speak_chars", 0) or 0)
if speak_limit > 0:
chunk_chars = min(chunk_chars, speak_limit)
self.daemon._event(
"gateway_read_start", key=read.key, start=read.start, chars=len(text)
)
spoken = 0
for offset, chunk in chunk_text(text, read.start, chunk_chars):
if stop.is_set() or self.daemon.stopping():
break
save_bookmark(read.bookmarks_path, read.key, offset, read.title)
self.daemon.speak(chunk)
spoken += 1
# A barge-in mutes playback synchronously on the audio thread;
# break promptly so we do not skip through suppressed chunks
# before the transcribed "stop" reaches `_handle`.
if stop.is_set() or self.daemon.muted():
break
if stop.is_set() or self.daemon.stopping():
self.daemon._event("gateway_read_interrupted", key=read.key, chunks=spoken)
else:
# Finished: park the bookmark at the end so a later request
# starts over rather than replaying the final chunk.
save_bookmark(read.bookmarks_path, read.key, len(text), read.title)
self.daemon._event("gateway_read_done", key=read.key, chunks=spoken)
finally:
with self._read_lock:
if self._read_stop is stop:
self._read_key = None
def _drop_pending_speech(self) -> None:
"""Discard replies already queued behind an interrupted one.
The daemon aborted the in-flight playback; anything waiting on the
outbound queue is output the user asked to stop, so it is dropped rather
than spoken next.
"""
outbound = self._outbound
if outbound is None:
return
dropped = 0
while True:
try:
message = outbound.get_nowait()
except queue.Empty:
break
if message is None:
outbound.put(None) # preserve the pump's shutdown sentinel
break
dropped += 1
if dropped:
self.daemon._event("gateway_speech_dropped", count=dropped)
def _on_barge_in(self, active: bool) -> None:
"""Daemon callback: mark a barge-in session (True) and its end (False)."""
self._barged_in = bool(active)
def _on_utterance(self, text: str) -> None: def _on_utterance(self, text: str) -> None:
text = (text or "").strip() text = (text or "").strip()
if not text: if not text:
return return
barge_in = self._barged_in
self._barged_in = False
self.daemon._event( self.daemon._event(
"gateway_message", "gateway_message",
contact_id=self.chat_id, contact_id=self.chat_id,
@@ -137,6 +323,6 @@ class VoiceAdapter(GatewayAdapter):
chat_type="dm", chat_type="dm",
contact_id=self.chat_id, contact_id=self.chat_id,
display_name=self.display_name, display_name=self.display_name,
raw={}, raw={"barge_in": True} if barge_in else {},
) )
) )
+9
View File
@@ -439,6 +439,15 @@ class LxmfDaemon:
except Exception: except Exception:
pass pass
def pending_sends(self) -> int:
"""How many outbound items are queued (a stream's backpressure signal).
A long-form read-aloud uses this to keep only a few messages queued
ahead, so stopping it takes effect promptly instead of after a large
backlog drains.
"""
return self._outbound.qsize()
# ---- identity ---- # ---- identity ----
def _load_identity(self, RNS): def _load_identity(self, RNS):
+348
View File
@@ -0,0 +1,348 @@
"""Ollama System One decision engine: ollama's native ``/v1/systemone`` API.
An alternative to the local SemIf llama.cpp engine (`engine.SemIfEngine`) and
to the Winnow server (`semif_agent.winnow.WinnowEngine`), selected per machine
with ``engine.provider == "ollama"`` in config.json — the same provider pattern
as ``llm`` / ``codegen``.
The agent's flat decision contract (state + question + typed options) maps onto
Ollama's System One ``choice`` question: the options become the question's
``criteria`` (id -> description, or ``null`` for a bare label) and the question
becomes its ``instructions``; the server returns a probability over exactly
those keys. This provider implements the **Ollama** shape of that API (the one
documented at docs.ollama.com/api/systemone), which differs from the Winnow
reference server in ways that matter at the edges:
* no ``/health`` route — reachability/warmth is probed through Ollama's native
``GET /api/version`` and ``POST /api/show`` (which also verifies the model
exists and advertises the ``decision`` capability);
* the decision context window is read from the model's ``num_ctx`` parameter
(``/api/show``) when ``engine.ollama.context_tokens`` is 0, so generated
skill bodies are sized to what the server really loaded;
* ``keep_alive`` is an Ollama request knob, not part of the System One contract;
* choice criteria descriptions are the Ollama subset ``string | null`` (never
an object) and at least two options are required;
* decision models do not generate text, so ``generate`` is unavailable here
(use ``llm.provider == "ollama"`` for the chat path).
The engine is real: any network, HTTP, or distribution failure raises
`EngineUnavailable`, which the scheduler treats as fatal — there is no fallback
model and no fabricated reply.
"""
from __future__ import annotations
import json
import math
import re
import threading
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from .decisions import DecisionRequest, DecisionResult
from .engine import DecisionEngine, EngineUnavailable
@dataclass
class OllamaSystemOneConfig:
"""Per-machine settings for the Ollama System One engine (`engine.ollama`)."""
#: The Ollama server root — **no** ``/v1`` suffix (System One lives at
#: ``/v1/systemone`` on the root server, unlike the OpenAI-compatible API).
base_url: str = "http://127.0.0.1:11434"
model: str = ""
#: The model's decision context window, in tokens. 0 asks the server (the
#: model's `num_ctx` parameter, then its architecture context length), so
#: the fidelity-state budget mirrors the window the server really loaded.
context_tokens: int = 16384
timeout: float = 120.0
#: Transient-failure retries before declaring the engine unavailable. 0
#: means a single attempt: an unreachable remote engine is fatal by
#: contract.
retries: int = 0
#: Bearer key for Ollama's cloud models (``https://ollama.com``); empty for
#: a local server.
api_key: str = ""
extra_headers: dict | None = None
user_agent: str = "semif-agent"
#: Ollama's model-unload policy for the request (a duration such as "5m",
#: or seconds). Empty keeps the server's own keep-alive setting.
keep_alive: str = ""
def _context_from_show(show: dict) -> int | None:
"""The model's context window from an Ollama ``/api/show`` payload.
Ollama reports ``parameters`` either as modelfile text
(``"num_ctx 16384\\n..."``) or as a mapping, depending on version; the
architecture context length in ``model_info`` is the fallback. Returns
``None`` when neither shape carries a usable number.
"""
params = show.get("parameters")
if isinstance(params, str):
match = re.search(r"(?m)^\s*num_ctx\s+(\d+)\s*$", params)
if match:
return int(match.group(1))
elif isinstance(params, dict):
value = params.get("num_ctx")
if value is not None:
try:
return int(value)
except (TypeError, ValueError):
pass
info = show.get("model_info")
if isinstance(info, dict):
# Prefer the text model's context length over a vision tower's.
candidates = [
value
for key, value in info.items()
if str(key).endswith(".context_length") and "vision" not in str(key)
]
for value in candidates:
try:
return int(value)
except (TypeError, ValueError):
continue
return None
class OllamaSystemOneEngine(DecisionEngine):
"""One Ollama System One endpoint, used for every decision.
Scoring maps a `DecisionRequest` -> a single ``choice`` question and reads
the returned distribution back over the requested option ids. The endpoint
is a single-slot server, so calls serialize on an internal lock exactly as
`SemIfEngine` serializes on its llama.cpp context.
"""
label = "ollama"
def __init__(self, config: OllamaSystemOneConfig):
self.config = config
self._lock = threading.Lock()
self._loaded = False
self._discovered_context: int | None = None
@property
def context_tokens(self) -> int:
configured = int(self.config.context_tokens or 0)
if configured > 0:
return configured
return int(self._discovered_context or 16384)
@property
def loaded(self) -> bool:
return self._loaded
# ---- transport ----
def _headers(self) -> dict:
headers = {
"content-type": "application/json",
"accept": "application/json",
}
if self.config.user_agent:
headers["user-agent"] = self.config.user_agent
if self.config.api_key:
headers["authorization"] = f"Bearer {self.config.api_key}"
for key, value in (self.config.extra_headers or {}).items():
headers[str(key)] = str(value)
return headers
def _request(self, path: str, payload: dict | None = None) -> dict:
"""GET (no payload) or POST JSON, or raise `EngineUnavailable`."""
url = self.config.base_url.rstrip("/") + path
data = None
if payload is not None:
data = json.dumps(payload).encode("utf-8")
attempts = max(0, int(self.config.retries)) + 1
last: Exception | None = None
for attempt in range(attempts):
request = urllib.request.Request(
url,
data=data,
method="POST" if data is not None else "GET",
headers=self._headers(),
)
try:
with urllib.request.urlopen(
request, timeout=self.config.timeout
) as response:
body = response.read().decode("utf-8", errors="replace")
parsed = json.loads(body)
if not isinstance(parsed, dict):
raise EngineUnavailable(
f"Ollama response from {url} is not a JSON object"
)
return parsed
except urllib.error.HTTPError as exc:
detail = ""
try:
# Ollama reports failures as {"error": "..."}.
detail = exc.read().decode("utf-8", errors="replace")[:300]
except Exception:
pass
last = EngineUnavailable(
f"HTTP {exc.code} from {url}: {detail}".strip()
)
# A 4xx (except 429) will not succeed on retry.
if 400 <= exc.code < 500 and exc.code != 429:
break
except EngineUnavailable:
raise
except Exception as exc: # URLError, timeout, socket, JSONDecodeError
last = exc
if attempt + 1 < attempts:
time.sleep(min(2.0**attempt, 5.0))
if isinstance(last, EngineUnavailable):
raise last
raise EngineUnavailable(
f"Ollama request to {url} failed: {type(last).__name__}: {last}"
)
def _post(self, path: str, payload: dict) -> dict:
return self._request(path, payload)
# ---- DecisionEngine ----
def warm(self) -> None:
"""Verify the server and the configured model, then mark loaded.
Ollama has no ``/health`` route: ``GET /api/version`` proves the server
answers and ``POST /api/show`` proves the model is pulled (404 when it
is not) and lets a 0 ``context_tokens`` follow the model's real
``num_ctx``. A model that advertises capabilities without ``decision``
is rejected with an actionable error instead of failing on first use.
"""
self._request("/api/version")
show = self._post("/api/show", {"model": self.config.model})
if int(self.config.context_tokens or 0) <= 0:
discovered = _context_from_show(show)
if discovered:
self._discovered_context = discovered
capabilities = show.get("capabilities")
if isinstance(capabilities, list) and capabilities:
if "decision" not in capabilities:
raise EngineUnavailable(
f"Ollama model {self.config.model!r} does not advertise the "
"'decision' capability (capabilities: "
f"{', '.join(str(c) for c in capabilities)}); point "
"engine.ollama.model at a System One model"
)
self._loaded = True
def call(self, request: DecisionRequest) -> DecisionResult:
option_ids = [option.id for option in request.options]
if len(option_ids) < 2:
raise EngineUnavailable(
"Ollama System One choice questions need at least two options"
)
state = request.state if isinstance(request.state, str) else json.dumps(
request.state
)
if not state.strip():
raise EngineUnavailable("Ollama System One requires a non-empty state")
# Ollama's choice criteria descriptions are `string | null`; a bare
# label is the explicit `null` form.
criteria = {
option.id: (option.description.strip() or None)
for option in request.options
}
payload = {
"model": self.config.model,
"state": state,
"questions": {
"decision": {
"type": "choice",
"instructions": request.question,
"criteria": criteria,
}
},
}
keep_alive = str(self.config.keep_alive or "").strip()
if keep_alive:
payload["keep_alive"] = keep_alive
with self._lock:
started = time.perf_counter()
body = self._post("/v1/systemone", payload)
elapsed = time.perf_counter() - started
answers = body.get("answers")
answer = answers.get("decision") if isinstance(answers, dict) else None
if not isinstance(answer, dict):
raise EngineUnavailable(
"Ollama response is missing answers.decision"
)
if answer.get("type") not in (None, "choice"):
raise EngineUnavailable(
f"Ollama answer type {answer.get('type')!r} is not 'choice'"
)
raw = answer.get("probabilities")
if not isinstance(raw, dict):
raise EngineUnavailable("Ollama answer is missing probabilities")
if set(raw) != set(option_ids):
raise EngineUnavailable(
"Ollama probabilities do not match the requested options: "
f"{sorted(raw)} != {sorted(option_ids)}"
)
choice = answer.get("choice")
if choice is not None and choice not in option_ids:
raise EngineUnavailable(
f"Ollama choice {choice!r} is not one of the requested options"
)
try:
values = [float(raw[option_id]) for option_id in option_ids]
except (TypeError, ValueError) as exc:
raise EngineUnavailable(
f"Ollama probabilities are not numeric: {exc}"
) from exc
if any(
(not math.isfinite(value)) or value < 0.0 or value > 1.0
for value in values
):
raise EngineUnavailable(
"Ollama returned a non-finite or out-of-range probability"
)
total = sum(values)
if total <= 0.0:
raise EngineUnavailable("Ollama returned an all-zero distribution")
probabilities = [value / total for value in values]
usage = body.get("usage") if isinstance(body.get("usage"), dict) else {}
self._loaded = True
return DecisionResult(
request=request,
option_ids=option_ids,
probabilities=probabilities,
extra={
"input_tokens": usage.get("input_tokens"),
"output_tokens": usage.get("output_tokens"),
"forward_seconds": elapsed,
"total_seconds": elapsed,
"raw_probability_sum": total,
"served_model": body.get("model"),
"choice": choice,
"confidence": answer.get("confidence"),
},
)
def generate(
self,
messages: list[dict],
temperature: float = 0.0,
max_tokens: int = 256,
) -> str:
"""Unavailable: System One decision models do not generate text.
Use ``llm.provider == "ollama"`` (an OpenAI-compatible chat endpoint) for
text; pointing ``llm.provider`` at this decision engine would ask a
classifier to write prose, so it is refused rather than faked.
"""
raise EngineUnavailable(
"the ollama System One decision engine does not generate text; "
"configure llm.provider = \"ollama\" for the chat path"
)
+140
View File
@@ -0,0 +1,140 @@
"""Long-form spoken reading: bookmark positions and speakable chunking.
A skill that resolves a long text (a book) asks the voice front end to read it
aloud; the front end streams it with text-to-speech one speakable chunk at a
time. The position reached is recorded in a ``bookmarks.json`` file beside the
saved text so a later request resumes where the listener stopped.
This module is neutral and stdlib-only: it knows nothing about the scheduler,
the gateway, or audio. The chunker is deterministic — the same text and start
offset always yield the same chunks — so a saved offset is always a valid
resume point.
"""
from __future__ import annotations
import json
import os
import time
from pathlib import Path
from typing import Iterator
#: The file (beside the saved books) that maps a book key -> last read offset.
BOOKMARKS_FILE = "bookmarks.json"
#: Default characters per spoken chunk. Kept below the voice front end's
#: `max_speak_chars` so a chunk is spoken whole, never truncated.
DEFAULT_CHUNK_CHARS = 300
_WHITESPACE = " \t\r\n"
_SENTENCE_END = ".!?"
def bookmarks_file(directory) -> Path:
"""The bookmarks path inside a books directory."""
return Path(directory) / BOOKMARKS_FILE
def load_bookmarks(path) -> dict:
"""Read the bookmarks map (``{key: {"offset", "title", "updated_at"}}``).
A missing or unparseable file is an empty map — bookmarks are an
optimization, never a reason a read fails.
"""
target = Path(path)
if not target.is_file():
return {}
try:
data = json.loads(target.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return data if isinstance(data, dict) else {}
def read_offset(path, key) -> int:
"""The last read offset recorded for `key` (0 when unset/unknown)."""
entry = load_bookmarks(path).get(str(key))
if isinstance(entry, dict):
try:
return max(0, int(entry.get("offset", 0)))
except (TypeError, ValueError):
return 0
if isinstance(entry, int): # tolerate a bare-offset legacy shape
return max(0, entry)
return 0
def save_bookmark(path, key, offset, title: str = "") -> None:
"""Record the read offset for `key`, atomically.
Written to a temp file and renamed so a reader never sees a half-written
map. Any filesystem failure is swallowed: a failed bookmark must not break
the reading itself.
"""
target = Path(path)
data = load_bookmarks(target)
data[str(key)] = {
"offset": max(0, int(offset)),
"title": str(title or ""),
"updated_at": time.time(),
}
try:
target.parent.mkdir(parents=True, exist_ok=True)
tmp = target.with_name(target.name + ".tmp")
tmp.write_text(
json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
os.replace(tmp, target)
except OSError:
pass
def _skip_whitespace(text: str, index: int) -> int:
while index < len(text) and text[index] in _WHITESPACE:
index += 1
return index
def _break_point(window: str) -> int:
"""How many characters of `window` to keep for one chunk.
Prefer a paragraph break, then a sentence end, then a whitespace break —
but only past the window's midpoint, so a break never yields a tiny chunk.
Falls back to the whole window when it holds no good boundary.
"""
half = len(window) // 2
paragraph = window.rfind("\n\n")
if paragraph >= half:
return paragraph + 2
for index in range(len(window) - 1, -1, -1):
if window[index] in _SENTENCE_END and (
index + 1 == len(window) or window[index + 1] in _WHITESPACE + "\"')]"
):
return index + 1
space = window.rfind(" ")
if space >= half:
return space + 1
return len(window)
def chunk_text(text: str, start: int = 0, max_chars: int = DEFAULT_CHUNK_CHARS) -> Iterator[tuple[int, str]]:
"""Yield ``(offset, chunk)`` speakable chunks of `text` from `start`.
`offset` is the absolute index of the chunk's first character in `text`, so
a front end can persist it as the resume point. Deterministic for a given
`text`, `start`, and `max_chars`.
"""
text = text or ""
total = len(text)
limit_chars = max(1, int(max_chars))
index = _skip_whitespace(text, max(0, int(start)))
while index < total:
window_end = min(index + limit_chars, total)
if window_end >= total:
end = total
else:
end = index + _break_point(text[index:window_end])
chunk = text[index:end].strip()
if chunk:
yield index, chunk
index = _skip_whitespace(text, end)
+13
View File
@@ -41,6 +41,7 @@ from .provider import ProviderError
from .packs import disabled_categories, load_packs, merge_packs from .packs import disabled_categories, load_packs, merge_packs
from .queue import RequestQueue from .queue import RequestQueue
from .skill import SkillRunner from .skill import SkillRunner
from .speech import SpeechService
from .timers import TimerService from .timers import TimerService
from .skills import ( from .skills import (
CANNED_CATEGORIES, CANNED_CATEGORIES,
@@ -436,6 +437,10 @@ 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"))
# Long-form read-aloud requests a skill posts for the voice front end.
# A body registers one and returns immediately; the gateway drains it
# and streams it with text-to-speech (see `semif_agent.speech`).
self.speech = SpeechService(trace=self.trace)
# Read-only introspection of the live tree for introspection skills # Read-only introspection of the live tree for introspection skills
# (listing categories / the skills in one), supplied as a locked # (listing categories / the skills in one), supplied as a locked
# snapshot so a body never reaches into the scheduler. # snapshot so a body never reaches into the scheduler.
@@ -444,6 +449,7 @@ class Scheduler:
engine=self.engine, engine=self.engine,
config=config, config=config,
timers=self.timers, timers=self.timers,
speech=self.speech,
admin=self, admin=self,
catalog=self.catalog, catalog=self.catalog,
) )
@@ -1064,6 +1070,13 @@ class Scheduler:
result=outcome.action_log or outcome.new_state or None, result=outcome.action_log or outcome.new_state or None,
) )
verdict = outcome.outcome or ("done" if outcome.success else "failed") verdict = outcome.outcome or ("done" if outcome.success else "failed")
if verdict == "continue" and self.speech.pending_for(request.id):
# The run handed off to a long-form read-aloud: the read IS the
# answer, so there is no further work for `assess:outcome` to find.
# Overriding to `done` keeps the chain from re-dispatching the
# request (which otherwise authors a spurious skill).
self.trace.append("read_aloud_terminal", request.id, skill=skill.name)
verdict = "done"
self.trace.append( self.trace.append(
"assessed", "assessed",
request.id, request.id,
+51 -5
View File
@@ -46,7 +46,7 @@ from .packs import SkillPack, pack_enabled
#: ``llm``/``codegen`` providers the wizard can emit. #: ``llm``/``codegen`` providers the wizard can emit.
PROVIDERS = ("semif", "ollama", "opencode", "openai") PROVIDERS = ("semif", "ollama", "opencode", "openai")
#: ``engine`` providers. #: ``engine`` providers.
ENGINE_PROVIDERS = ("semif", "winnow") ENGINE_PROVIDERS = ("semif", "winnow", "ollama")
#: New-skill creation modes. #: New-skill creation modes.
AUTHORING_MODES = ("deny", "ask", "allow") AUTHORING_MODES = ("deny", "ask", "allow")
@@ -71,10 +71,14 @@ class Answers:
"""The wizard's answers, and the source of truth for the generated config.""" """The wizard's answers, and the source of truth for the generated config."""
# Decision engine. # Decision engine.
engine_provider: str = "semif" # semif | winnow engine_provider: str = "semif" # semif | winnow | ollama
winnow_base_url: str = "" winnow_base_url: str = ""
winnow_model: str = "" winnow_model: str = ""
winnow_api_key: str = "" winnow_api_key: str = ""
#: Ollama's native System One route (`engine.ollama`).
ollama_base_url: str = ""
ollama_model: str = ""
ollama_api_key: str = ""
# New-skill authoring: deny | ask | allow. # New-skill authoring: deny | ask | allow.
new_skill_creation: str = "deny" new_skill_creation: str = "deny"
@@ -351,7 +355,7 @@ def run_interview(
output( output(
" The decision engine routes every request. It runs locally on the\n" " The decision engine routes every request. It runs locally on the\n"
" pinned SemIf 4B GGUF by default (no network), or against a remote\n" " pinned SemIf 4B GGUF by default (no network), or against a remote\n"
" Winnow /v1/systemone server." " Winnow /v1/systemone server or an Ollama System One decision model."
) )
answers.engine_provider = _ask_choice( answers.engine_provider = _ask_choice(
input_fn, input_fn,
@@ -360,6 +364,7 @@ def run_interview(
[ [
("semif", "local SemIf 4B (llama.cpp, pinned GGUF)"), ("semif", "local SemIf 4B (llama.cpp, pinned GGUF)"),
("winnow", "remote Winnow decision server"), ("winnow", "remote Winnow decision server"),
("ollama", "remote Ollama System One model (/v1/systemone)"),
], ],
1, 1,
) )
@@ -376,6 +381,25 @@ def run_interview(
answers.winnow_api_key = _ask_text( answers.winnow_api_key = _ask_text(
input_fn, output, " winnow API key (blank for none)", "", secret=True input_fn, output, " winnow API key (blank for none)", "", secret=True
) )
elif answers.engine_provider == "ollama":
answers.ollama_base_url = _ask_text(
input_fn, output, " ollama base URL", "http://127.0.0.1:11434"
)
model = ""
while not model:
model = _ask_text(
input_fn, output, " ollama System One model (required)"
)
if not model:
output(" engine.ollama.model is required.")
answers.ollama_model = model
answers.ollama_api_key = _ask_text(
input_fn,
output,
" ollama API key (blank for a local server)",
"",
secret=True,
)
# 2. Skill authoring. # 2. Skill authoring.
output("") output("")
@@ -399,7 +423,15 @@ def run_interview(
answers.new_skill_creation = mode answers.new_skill_creation = mode
if mode != "deny": if mode != "deny":
output("") output("")
_collect_llm(input_fn, output, answers, label="llm", allow_semif=True) # The Ollama System One decision model does not generate text, so it
# cannot back the small `llm` task; only a real endpoint can.
_collect_llm(
input_fn,
output,
answers,
label="llm",
allow_semif=answers.engine_provider != "ollama",
)
output("") output("")
_collect_llm(input_fn, output, answers, label="codegen", allow_semif=False) _collect_llm(input_fn, output, answers, label="codegen", allow_semif=False)
@@ -529,6 +561,14 @@ def build_config(answers: Answers, packs: Sequence[SkillPack]) -> dict:
_set_secret_or_literal( _set_secret_or_literal(
winnow, "api_key", answers.winnow_api_key, "engine_winnow_api_key" winnow, "api_key", answers.winnow_api_key, "engine_winnow_api_key"
) )
elif answers.engine_provider == "ollama":
ollama = engine.setdefault("ollama", {})
if answers.ollama_base_url:
ollama["base_url"] = answers.ollama_base_url
ollama["model"] = answers.ollama_model
_set_secret_or_literal(
ollama, "api_key", answers.ollama_api_key, "engine_ollama_api_key"
)
# Authoring mode. # Authoring mode.
config["new_skill_creation"] = answers.new_skill_creation config["new_skill_creation"] = answers.new_skill_creation
@@ -613,6 +653,8 @@ def build_secrets(answers: Answers) -> dict:
secrets: dict[str, str] = {} secrets: dict[str, str] = {}
if answers.engine_provider == "winnow" and answers.winnow_api_key: if answers.engine_provider == "winnow" and answers.winnow_api_key:
secrets["engine_winnow_api_key"] = answers.winnow_api_key secrets["engine_winnow_api_key"] = answers.winnow_api_key
if answers.engine_provider == "ollama" and answers.ollama_api_key:
secrets["engine_ollama_api_key"] = answers.ollama_api_key
if answers.llm_provider != "semif" and answers.llm_api_key: if answers.llm_provider != "semif" and answers.llm_api_key:
secrets["llm_api_key"] = answers.llm_api_key secrets["llm_api_key"] = answers.llm_api_key
if answers.codegen_api_key: if answers.codegen_api_key:
@@ -834,7 +876,11 @@ def _print_summary(answers: Answers, output: Callable[[str], None]) -> None:
+ ( + (
"local SemIf 4B" "local SemIf 4B"
if answers.engine_provider == "semif" if answers.engine_provider == "semif"
else f"remote Winnow ({answers.winnow_model or '?'})" else (
f"remote Winnow ({answers.winnow_model or '?'})"
if answers.engine_provider == "winnow"
else f"remote Ollama System One ({answers.ollama_model or '?'})"
)
) )
) )
output(f" authoring: {answers.new_skill_creation}") output(f" authoring: {answers.new_skill_creation}")
+3
View File
@@ -148,6 +148,9 @@ class SkillRunner:
engine=self.ctx.engine, engine=self.ctx.engine,
config=merged, config=merged,
timers=self.ctx.timers, timers=self.ctx.timers,
# The scheduler's speech channel (a skill can post a long-form
# read-aloud for a voice front end) rides on every run.
speech=self.ctx.speech,
# `admin` (mutation of the agent) is reserved for the built-in # `admin` (mutation of the agent) is reserved for the built-in
# housekeeping meta skills; an ordinary body only ever gets the # housekeeping meta skills; an ordinary body only ever gets the
# read-only `catalog`. # read-only `catalog`.
+6
View File
@@ -26,6 +26,7 @@ from .decisions import DecisionRequest, Option, Request
from .engine import DecisionEngine from .engine import DecisionEngine
from .llm import LLMClient from .llm import LLMClient
from .log import DecisionLog from .log import DecisionLog
from .speech import SpeechService
from .timers import TimerService from .timers import TimerService
from .trace import TraceLog from .trace import TraceLog
@@ -45,6 +46,11 @@ class ActionContext:
engine: DecisionEngine engine: DecisionEngine
config: dict config: dict
timers: TimerService | None = None timers: TimerService | None = None
#: The scheduler's speech channel. A body that resolves a long text to be
#: read aloud (a book) registers it here and returns immediately; the voice
#: front end streams it and the user stops it. None for a body running
#: without a scheduler (a test) — callers must tolerate None.
speech: SpeechService | None = None
# The scheduler, exposed to built-in meta skills (housekeeping) so they can # 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 (the read-only `catalog` is their view). # must never reach into the agent (the read-only `catalog` is their view).
+164
View File
@@ -0,0 +1,164 @@
"""The scheduler's speech channel: a long-form read-aloud request for a front end.
A skill body cannot speak: it runs inside the scheduler, which is transport-
agnostic and must never reach into a front end. So a body that resolves a long
text to be *read aloud* registers a `ReadAloud` here (through `ctx.speech`) and
returns immediately. The gateway that owns the originating chat drains the
request (`drain()`) and hands it to the platform adapter, which streams it with
text-to-speech until the user stops it. Position is tracked in a
``bookmarks.json`` beside the text (see `semif_agent.reading`).
This mirrors `semif_agent.timers`: the scheduler exposes a small thread-safe
service; a front end drains what it can deliver. It is neutral — stdlib only,
and it knows nothing about audio or any specific gateway.
"""
from __future__ import annotations
import threading
import time
import uuid
from collections import deque
from dataclasses import dataclass, field
from .reading import DEFAULT_CHUNK_CHARS
@dataclass
class ReadAloud:
"""One queued request to read a saved text aloud from a position.
`path` is the text file; `bookmarks_path` the ``bookmarks.json`` beside it;
`key` the book's bookmark key; `start` the character offset to resume from.
`source` is the originating front-end source (`"voice:<chat_id>"`) and
`run_id` the run that asked, so the gateway can route it to the right chat.
"""
path: str
key: str
bookmarks_path: str
run_id: str = ""
source: str = ""
title: str = ""
start: int = 0
chunk_chars: int = DEFAULT_CHUNK_CHARS
id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
created_at: float = field(default_factory=time.time)
class SpeechService:
"""Holds read-aloud requests until a front end drains them.
Bounded like the request queue: a front end that never drains (the REPL)
cannot grow it without limit.
"""
def __init__(self, trace=None, max_pending: int = 64):
self.trace = trace
self._lock = threading.Lock()
self._pending: deque[ReadAloud] = deque(maxlen=max(1, int(max_pending)))
#: Optional predicate set by a front end: whether a given source can be
#: streamed to (the voice gateway; an LXMF voice chat). None means no
#: front end is attached (the REPL, a test), so nothing supports it.
self._stream_check = None
def set_stream_check(self, check) -> None:
"""Register the front end's per-source streaming capability predicate.
Called by the gateway service with a callable `(source) -> bool` so a
skill can ask `supports(source)` before it posts a read-aloud. A front
end that cannot stream (or has none attached) leaves it None.
"""
self._stream_check = check if callable(check) else None
def supports(self, source: str) -> bool:
"""Whether the front end can stream a read-aloud to `source`.
False when no front end is attached, when the source's platform cannot
stream, or when the check raises — the caller then keeps its normal
(non-read-aloud) behaviour.
"""
check = self._stream_check
if check is None:
return False
try:
return bool(check(str(source or "")))
except Exception:
return False
def read_aloud(
self,
*,
path: str,
key: str,
bookmarks_path: str,
run_id: str = "",
source: str = "",
title: str = "",
start: int = 0,
chunk_chars: int = DEFAULT_CHUNK_CHARS,
) -> ReadAloud:
"""Queue a text to be read aloud. Returns the queued request."""
read = ReadAloud(
path=str(path),
key=str(key),
bookmarks_path=str(bookmarks_path),
run_id=str(run_id or ""),
source=str(source or ""),
title=str(title or ""),
start=max(0, int(start or 0)),
chunk_chars=max(1, int(chunk_chars or DEFAULT_CHUNK_CHARS)),
)
with self._lock:
self._pending.append(read)
self._event(
"read_aloud_queued",
read.run_id,
read_id=read.id,
key=read.key,
source=read.source,
start=read.start,
)
return read
def drain(self) -> list[ReadAloud]:
"""Pop and return the queued requests, oldest first (for a front end)."""
with self._lock:
reads = list(self._pending)
self._pending.clear()
return reads
def pending_for(self, run_id: str) -> bool:
"""Whether a read-aloud is queued for a run (not yet drained).
Lets the scheduler treat a run that handed off to a long-form read as
complete: the read is the answer, so `assess:outcome` has no further
work to find and must not re-dispatch the request.
"""
with self._lock:
return any(r.run_id == str(run_id) for r in self._pending)
def pending(self) -> list[dict]:
"""A snapshot of the queue (for the dashboard)."""
with self._lock:
return [
{
"id": r.id,
"run_id": r.run_id,
"source": r.source,
"key": r.key,
"title": r.title,
"start": r.start,
"path": r.path,
"created_at": r.created_at,
}
for r in self._pending
]
def _event(self, kind: str, run_id: str, **fields) -> None:
if self.trace is None:
return
try:
self.trace.append(kind, run_id, **fields)
except Exception:
pass
+212 -42
View File
@@ -15,8 +15,14 @@ Audio contract: 16 kHz, mono, signed 16-bit little-endian PCM, read in fixed
resampling is done in the loop. resampling is done in the loop.
Design notes: Design notes:
- **Half-duplex.** Capture frames are discarded while a reply is being spoken, - **Half-duplex by default, barge-in optional.** Capture frames are normally
so the agent never transcribes its own voice (no barge-in yet). discarded while a reply is being spoken, so the agent never transcribes its
own voice. With barge-in enabled (`barge_in.enabled`), the wake word is still
scored during playback: the user can interrupt a spoken reply, the playback
is aborted, and the following command is captured and handed to the front end
(which decides whether it is a stop or a new request). Speech is muted while
the interrupt command is captured and handled, so the interrupted reply does
not resume over the user.
- The engine interfaces are plain classes so tests can inject fakes and drive - The engine interfaces are plain classes so tests can inject fakes and drive
the loop without hardware or the optional packages. the loop without hardware or the optional packages.
""" """
@@ -150,6 +156,17 @@ class AudioIO:
def write(self, pcm16: bytes, sample_rate: int) -> None: def write(self, pcm16: bytes, sample_rate: int) -> None:
raise NotImplementedError raise NotImplementedError
def play(self, pcm16: bytes, sample_rate: int, stop_event=None) -> bool:
"""Play PCM, returning `False` if aborted early via `stop_event`.
The default plays the whole buffer in one `write`. The real device
overrides this to stream in small chunks so a barge-in stops the reply
promptly instead of after the whole buffer; a fake that only implements
`write` still plays through here.
"""
self.write(pcm16, sample_rate)
return True
def flush(self) -> None: def flush(self) -> None:
"""Drop any buffered capture frames (called after speaking to clear echo).""" """Drop any buffered capture frames (called after speaking to clear echo)."""
@@ -562,6 +579,40 @@ class SoundDeviceAudio(AudioIO):
) as stream: ) as stream:
stream.write(pcm16) stream.write(pcm16)
def play(self, pcm16: bytes, sample_rate: int, stop_event=None) -> bool:
"""Stream PCM in small chunks so a barge-in can abort playback.
A single `write` of the whole buffer blocks until the device drains it,
so an interrupt could only take effect after the reply had finished. The
buffer is played in ~50 ms chunks instead, checking `stop_event` between
them; on a stop the stream is aborted (discarding what is still buffered)
and `False` is returned. One output stream is opened for the whole
buffer, so the chunks play gaplessly.
"""
import sounddevice as sd
rate = self.output_sample_rate or self._device_rate(
self.output_device, "output"
)
if rate != int(sample_rate):
pcm16 = _resample_pcm16(pcm16, int(sample_rate), rate)
chunk = max(BYTES_PER_SAMPLE, int(rate * 0.05) * BYTES_PER_SAMPLE) # 50 ms
with sd.RawOutputStream(
samplerate=rate,
channels=1,
dtype="int16",
device=self.output_device,
) as stream:
for offset in range(0, len(pcm16), chunk):
if stop_event is not None and stop_event.is_set():
try:
stream.abort()
except Exception:
pass
return False
stream.write(pcm16[offset : offset + chunk])
return True
def flush(self) -> None: def flush(self) -> None:
try: try:
while not self._frames.empty(): while not self._frames.empty():
@@ -889,7 +940,7 @@ class VoiceDaemon:
""" """
def __init__(self, cfg: dict | None = None, trace=None, engines: VoiceEngines | None = None, def __init__(self, cfg: dict | None = None, trace=None, engines: VoiceEngines | None = None,
name: str = "voice", input_ready=None): name: str = "voice", input_ready=None, on_barge_in=None):
cfg = cfg or {} cfg = cfg or {}
self.config = cfg self.config = cfg
self.trace = trace self.trace = trace
@@ -899,6 +950,11 @@ class VoiceDaemon:
#: is still running the current request), so a second command cannot be #: is still running the current request), so a second command cannot be
#: started before the first reaches a result. None = always ready. #: started before the first reaches a result. None = always ready.
self.input_ready = input_ready self.input_ready = input_ready
#: Optional callback the loop invokes around a barge-in: `True` when the
#: wake word is heard over a spoken reply (playback aborted, listening
#: begins), `False` once that listening session ends. The front end uses
#: it to classify the following utterance as an interrupt.
self.on_barge_in = on_barge_in
self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.2)) self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.2))
#: After the wake word, how long to wait for the command's speech to #: After the wake word, how long to wait for the command's speech to
#: begin before giving up (a natural pause after "hey <word>" — e.g. #: begin before giving up (a natural pause after "hey <word>" — e.g.
@@ -944,12 +1000,29 @@ class VoiceDaemon:
self.cue_submit_notes = _parse_notes(cue.get("submit_notes")) self.cue_submit_notes = _parse_notes(cue.get("submit_notes"))
self.cue_note_gap_ms = int(cue.get("note_gap_ms", 20) or 0) self.cue_note_gap_ms = int(cue.get("note_gap_ms", 20) or 0)
#: Barge-in: keep scoring the wake word while a reply is playing, abort
#: the playback on a wake, and mute speech while the interrupt command
#: is captured/handled. `wait_s` bounds how long to wait for the
#: interrupted playback to release the audio device. `threshold`
#: overrides the wake threshold for barge-in only (a higher bar keeps
#: the agent's own TTS from self-triggering; 0 = use `wake.threshold`).
barge_cfg = cfg.get("barge_in", {}) or {}
self.barge_in_enabled = bool(barge_cfg.get("enabled", True))
self.barge_in_wait_s = float(barge_cfg.get("wait_s", 2.0) or 0.0)
self.barge_in_threshold = (
float(barge_cfg.get("threshold", 0.0) or 0.0) or self.wake_threshold
)
self._engines = engines self._engines = engines
self._engines_lock = threading.Lock() self._engines_lock = threading.Lock()
self._audio_lock = threading.Lock() # serialize cue/speak playback self._audio_lock = threading.Lock() # serialize cue/speak playback
self._on_utterance: UtteranceHandler | None = None self._on_utterance: UtteranceHandler | None = None
self._stop = threading.Event() self._stop = threading.Event()
self._speaking = threading.Event() self._speaking = threading.Event()
#: Set while a reply is being played; `_interrupt` aborts that playback.
self._interrupt = threading.Event()
#: While set, `speak` drops text (a barge-in is being captured/handled).
self._mute = threading.Event()
# ---- requirements ---- # ---- requirements ----
@@ -1022,49 +1095,111 @@ class VoiceDaemon:
return return
if not pcm: if not pcm:
continue continue
barge_in = False
if self._speaking.is_set(): if self._speaking.is_set():
continue # Half-duplex by default: the agent's own voice is discarded.
score = engines.wake.score(pcm) # With barge-in enabled the wake word is still scored, so the
if score < self.wake_threshold: # user can interrupt a spoken reply ("hey <word>, stop").
continue if not self.barge_in_enabled:
if self.input_ready is not None and not self.input_ready(): continue
# The single scheduler slot is still running the current score = engines.wake.score(pcm)
# request: hold the wake word until it reaches a result (or if score < self.barge_in_threshold:
# pauses for the user's answer), so a new command cannot start continue
# while one is in flight. Reset the detector so the same wake barge_in = True
# phrase does not immediately re-fire once the slot frees. self._begin_barge_in(engines, score)
else:
score = engines.wake.score(pcm)
if score < self.wake_threshold:
continue
delivered = False
try:
if self.input_ready is not None and not self.input_ready():
# The single scheduler slot is still running the current
# request: hold the wake word until it reaches a result (or
# pauses for the user's answer), so a new command cannot
# start while one is in flight. Reset the detector so the
# same wake phrase does not immediately re-fire once the
# slot frees.
try:
engines.wake.reset()
except Exception:
pass
self._event("voice_wake_blocked", score=round(float(score), 3))
continue
if not barge_in:
self._event("voice_wake", score=round(float(score), 3))
try: try:
engines.wake.reset() engines.wake.reset()
except Exception: except Exception:
pass pass
self._event("voice_wake_blocked", score=round(float(score), 3)) self._cue(self.cue_frequency, self.cue_duration_ms)
continue # Wait for the command to start rather than assuming it is glued
self._event("voice_wake", score=round(float(score), 3)) # to the wake word (the wake frame + a natural pause are
# discarded so the command is not truncated).
wait_for_speech_ms = self.listen_timeout_ms
utterance = self._collect(engines, pcm, wait_for_speech_ms=wait_for_speech_ms)
if not utterance:
continue
try:
text = engines.stt.transcribe(utterance)
except Exception as exc:
self._event("voice_stt_failed", message=str(exc)[:300])
continue
text = (text or "").strip()
if not text:
self._event("voice_stt_empty", samples=len(utterance) // BYTES_PER_SAMPLE)
continue
self._event("voice_transcribed", chars=len(text))
self._bling()
delivered = True
if self._on_utterance is not None:
self._on_utterance(text)
finally:
if barge_in:
self._end_barge_in(delivered)
def _begin_barge_in(self, engines: VoiceEngines, score: float) -> None:
"""Abort the current reply and start listening for an interrupt.
The playback is stopped (the daemon's `play` watches `_interrupt`) and
speech is muted so the interrupted reply cannot resume over the user
while the interrupt command is captured and handled. The front end is
told via `on_barge_in(True)` so it can classify the next utterance.
"""
self._event("voice_barge_in", score=round(float(score), 3))
self._mute.set()
self._interrupt.set()
if self.on_barge_in is not None:
try: try:
engines.wake.reset() self.on_barge_in(True)
except Exception: except Exception:
pass pass
self._cue(self.cue_frequency, self.cue_duration_ms) # Wait for the interrupted playback to release the audio device so the
# Wait for the command to start rather than assuming it is glued to # wake cue and the captured command are not played over it.
# the wake word (the wake frame + a natural pause are discarded so deadline = time.time() + self.barge_in_wait_s
# the command is not truncated). while self._speaking.is_set() and time.time() < deadline:
wait_for_speech_ms = self.listen_timeout_ms time.sleep(0.005)
utterance = self._collect(engines, pcm, wait_for_speech_ms=wait_for_speech_ms) try:
if not utterance: engines.audio.flush() # drop the reply's echo captured while speaking
continue except Exception:
pass
def _end_barge_in(self, delivered: bool) -> None:
"""Close a barge-in session.
`delivered` is True when a command was transcribed and handed to the
front end; the front end then owns un-muting (it un-mutes only after the
interrupt has been handled, so the interrupted reply never resumes). A
barge-in that captured nothing un-mutes here.
"""
self._interrupt.clear()
if self.on_barge_in is not None:
try: try:
text = engines.stt.transcribe(utterance) self.on_barge_in(False)
except Exception as exc: except Exception:
self._event("voice_stt_failed", message=str(exc)[:300]) pass
continue if not delivered or self.on_barge_in is None:
text = (text or "").strip() self._mute.clear()
if not text:
self._event("voice_stt_empty", samples=len(utterance) // BYTES_PER_SAMPLE)
continue
self._event("voice_transcribed", chars=len(text))
self._bling()
if self._on_utterance is not None:
self._on_utterance(text)
def _collect(self, engines: VoiceEngines, first_frame: bytes, wait_for_speech_ms: int = 0) -> bytes: def _collect(self, engines: VoiceEngines, first_frame: bytes, wait_for_speech_ms: int = 0) -> bytes:
"""Accumulate frames from the wake word until trailing silence. """Accumulate frames from the wake word until trailing silence.
@@ -1243,15 +1378,42 @@ class VoiceDaemon:
except Exception as exc: except Exception as exc:
self._event("voice_cue_failed", message=str(exc)[:200]) self._event("voice_cue_failed", message=str(exc)[:200])
def set_muted(self, muted: bool) -> None:
"""Mute/unmute spoken replies (used around a barge-in)."""
if muted:
self._mute.set()
else:
self._mute.clear()
def muted(self) -> bool:
"""Whether spoken replies are currently muted (a barge-in is in flight)."""
return self._mute.is_set()
def stopping(self) -> bool:
"""Whether the daemon is shutting down (a long stream should stop)."""
return self._stop.is_set()
def speak(self, text: str) -> None: def speak(self, text: str) -> None:
"""Synthesize and play `text`; called from the outbound pump thread.""" """Synthesize and play `text`; called from the outbound pump thread."""
text = (text or "").strip() text = (text or "").strip()
if not text: if not text:
return return
if self._mute.is_set():
# A barge-in is in progress: the user interrupted and is giving a
# new command, so a pending reply is dropped rather than played over
# them. Replies after the interrupt is handled are spoken normally.
self._event("voice_speak_suppressed", chars=len(text))
return
if self.max_speak_chars and len(text) > self.max_speak_chars: if self.max_speak_chars and len(text) > self.max_speak_chars:
clipped = text[: self.max_speak_chars].rsplit(" ", 1)[0] clipped = text[: self.max_speak_chars].rsplit(" ", 1)[0]
text = (clipped or text[: self.max_speak_chars]) + "…" text = (clipped or text[: self.max_speak_chars]) + "…"
engines = self._ensure_engines() engines = self._ensure_engines()
# Start from a clean wake-detector state so the reply's own audio does
# not inherit a stale partial match.
try:
engines.wake.reset()
except Exception:
pass
self._speaking.set() self._speaking.set()
self._event("voice_speak_start", chars=len(text)) self._event("voice_speak_start", chars=len(text))
try: try:
@@ -1266,11 +1428,19 @@ class VoiceDaemon:
else 0.0, else 0.0,
) )
if pcm: if pcm:
with self._audio_lock: if self._interrupt.is_set():
engines.audio.open_output(sample_rate) # A barge-in landed during synthesis; skip playback.
# The instant the first reply audio is handed to the device. self._event("voice_speak_aborted", chars=len(text))
self._event("voice_playback_start", ts=time.time(), chars=len(text)) else:
engines.audio.write(pcm, sample_rate) with self._audio_lock:
engines.audio.open_output(sample_rate)
# The instant the first reply audio is handed to the device.
self._event("voice_playback_start", ts=time.time(), chars=len(text))
completed = engines.audio.play(
pcm, sample_rate, stop_event=self._interrupt
)
if not completed:
self._event("voice_speak_interrupted", chars=len(text))
self._event("voice_spoke", chars=len(text)) self._event("voice_spoke", chars=len(text))
except Exception as exc: except Exception as exc:
self._event("voice_speak_failed", message=str(exc)[:300]) self._event("voice_speak_failed", message=str(exc)[:300])
+7 -5
View File
@@ -8,10 +8,12 @@ question type: the options become the question's ``criteria`` (id -> description
and the question becomes its ``instructions``; the server returns a probability and the question becomes its ``instructions``; the server returns a probability
over exactly those keys. over exactly those keys.
Winnow runs as its own process (``winnow-server``); see ``local/ENVIRONMENT.md`` It works against any server implementing that route: the reference
for this deployment. The engine is real: any network, HTTP, or distribution ``winnow-server``, or an OpenAI-compatible host (ollama 0.40+) serving a
failure raises `EngineUnavailable`, which the scheduler treats as fatal — there ``decision`` model such as ``clef-flash``. See ``local/ENVIRONMENT.md`` for this
is no fallback model and no fabricated reply. deployment. The engine is real: any network, HTTP, or distribution failure
raises `EngineUnavailable`, which the scheduler treats as fatal — there is no
fallback model and no fabricated reply.
""" """
from __future__ import annotations from __future__ import annotations
@@ -24,7 +26,7 @@ import urllib.error
import urllib.request import urllib.request
from dataclasses import dataclass from dataclasses import dataclass
from .decisions import DecisionRequest, DecisionResult from .decisions import DecisionRequest, DecisionResult, Option
from .engine import DecisionEngine, EngineUnavailable from .engine import DecisionEngine, EngineUnavailable
+30
View File
@@ -19,6 +19,7 @@ from semif_agent.engine import (
_install_gpu_state_reset, _install_gpu_state_reset,
_offloading_params, _offloading_params,
) )
from semif_agent.ollama_systemone import OllamaSystemOneEngine
from semif_agent.winnow import WinnowEngine from semif_agent.winnow import WinnowEngine
PINS = { PINS = {
@@ -111,3 +112,32 @@ def test_build_engine_selects_the_winnow_provider():
def test_build_engine_winnow_requires_a_model(): def test_build_engine_winnow_requires_a_model():
with pytest.raises(SystemExit): with pytest.raises(SystemExit):
build_engine({"engine": {"provider": "winnow", "winnow": {}}}, PINS) build_engine({"engine": {"provider": "winnow", "winnow": {}}}, PINS)
def test_build_engine_selects_the_ollama_systemone_provider():
engine = build_engine(
{
"engine": {
"provider": "ollama",
"ollama": {
"base_url": "http://example:11434",
"model": "clef-flash",
"context_tokens": 8192,
"keep_alive": "5m",
},
}
},
PINS,
)
assert isinstance(engine, OllamaSystemOneEngine)
assert isinstance(engine, DecisionEngine)
assert engine.label == "ollama"
assert engine.config.base_url == "http://example:11434"
assert engine.config.model == "clef-flash"
assert engine.context_tokens == 8192
assert engine.config.keep_alive == "5m"
def test_build_engine_ollama_requires_a_model():
with pytest.raises(SystemExit):
build_engine({"engine": {"provider": "ollama", "ollama": {}}}, PINS)
+272
View File
@@ -894,6 +894,230 @@ def test_lxmf_voice_reply_bounds_length(monkeypatch):
assert len(synth.calls[0]) <= 10 assert len(synth.calls[0]) <= 10
# ---- LXMF read-aloud (a book streamed as voice messages) -------------------
def _read_aloud(chat, path, bookmarks, start=0, key="k", title="T"):
from semif_agent.speech import ReadAloud
return ReadAloud(
path=str(path),
key=key,
bookmarks_path=str(bookmarks),
source=f"lxmf:{chat}",
start=start,
title=title,
)
def _drain_lxmf_daemon(adapter):
items = []
while not adapter.daemon._outbound.empty():
items.append(adapter.daemon._outbound.get_nowait())
return items
def test_lxmf_speech_stream_ready_only_for_voice_chats():
from semif_agent.gateway.lxmf import LxmfAdapter
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
synthesizer=FakeSynthesizer(),
)
assert adapter.supports_speech_stream is True
assert adapter.speech_stream_ready("ab") is False
adapter._mark_voice_chat("ab")
assert adapter.speech_stream_ready("ab") is True
# Voice replies off: no read-aloud at all.
off = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True, "reply_with_voice": False}},
synthesizer=FakeSynthesizer(),
)
off._mark_voice_chat("ab")
assert off.supports_speech_stream is False
assert off.speech_stream_ready("ab") is False
def test_lxmf_streams_a_read_aloud_as_voice_messages(tmp_path, monkeypatch):
import semif_agent.gateway.lxmf as lxmf
from semif_agent.gateway.lxmf import LxmfAdapter
from semif_agent.reading import read_offset
monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG")
chat = "ab" * 16
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True, "read": {"max_lead": 100000}}},
synthesizer=FakeSynthesizer(),
)
adapter._mark_voice_chat(chat)
text = "Sentence one. " * 80
book = tmp_path / "book.txt"
book.write_text(text, encoding="utf-8")
bookmarks = tmp_path / "bookmarks.json"
adapter._stream(_read_aloud(chat, book, bookmarks))
items = _drain_lxmf_daemon(adapter)
assert len(items) > 1, "the book must be sent as several messages"
assert all(item[0] == chat for item in items)
assert all(item[2] == b"OGG" for item in items)
# The chunks reconstruct the text, and completion parks the bookmark at the end.
assert "".join(item[1] for item in items).replace(" ", "") == text.replace(" ", "")
assert read_offset(bookmarks, "k") == len(text)
def test_lxmf_read_aloud_stops_on_a_stop_command(tmp_path, monkeypatch):
import semif_agent.gateway.lxmf as lxmf
from semif_agent.gateway.lxmf import LxmfAdapter
from semif_agent.reading import read_offset
monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG")
chat = "ab" * 16
seen: list = []
class StoppingSynth(FakeSynthesizer):
def synthesize(self, text):
if len(self.calls) == 1: # during the second chunk
adapter._deliver({"source_hash": chat}, "stop")
return super().synthesize(text)
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
synthesizer=StoppingSynth(),
)
adapter._on_inbound = seen.append
adapter._mark_voice_chat(chat)
text = "Sentence one. " * 80
book = tmp_path / "book.txt"
book.write_text(text, encoding="utf-8")
bookmarks = tmp_path / "bookmarks.json"
adapter._stream(_read_aloud(chat, book, bookmarks))
assert seen == [], "a bare stop must not be submitted as a request"
items = _drain_lxmf_daemon(adapter)
assert len(items) == 2, "the read stops at the next chunk"
offset = read_offset(bookmarks, "k")
assert 0 < offset < len(text)
def test_lxmf_new_command_stops_the_read_and_is_forwarded(tmp_path, monkeypatch):
import semif_agent.gateway.lxmf as lxmf
from semif_agent.gateway.lxmf import LxmfAdapter
monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG")
chat = "ab" * 16
seen: list = []
class StoppingSynth(FakeSynthesizer):
def synthesize(self, text):
if len(self.calls) == 1:
adapter._deliver({"source_hash": chat}, "what time is it")
return super().synthesize(text)
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
synthesizer=StoppingSynth(),
)
adapter._on_inbound = seen.append
adapter._mark_voice_chat(chat)
book = tmp_path / "book.txt"
book.write_text("Sentence one. " * 80, encoding="utf-8")
adapter._stream(_read_aloud(chat, book, tmp_path / "bookmarks.json"))
assert [m.text for m in seen] == ["what time is it"]
def test_lxmf_read_aloud_skips_a_non_voice_chat(tmp_path, monkeypatch):
import semif_agent.gateway.lxmf as lxmf
from semif_agent.gateway.lxmf import LxmfAdapter
monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG")
chat = "ab" * 16
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
synthesizer=FakeSynthesizer(),
)
# Not marked as a voice chat: nothing is streamed.
book = tmp_path / "book.txt"
book.write_text("Sentence one. " * 80, encoding="utf-8")
adapter._stream(_read_aloud(chat, book, tmp_path / "bookmarks.json"))
assert _drain_lxmf_daemon(adapter) == []
def test_lxmf_read_aloud_backpressures_the_outbound_queue(tmp_path, monkeypatch):
# The stream keeps only a few messages queued ahead, so a stop is prompt
# even though the transport sends them slowly.
import threading
import semif_agent.gateway.lxmf as lxmf
from semif_agent.gateway.lxmf import LxmfAdapter
monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG")
chat = "ab" * 16
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True, "read": {"max_lead": 3}}},
synthesizer=FakeSynthesizer(),
)
adapter._mark_voice_chat(chat)
book = tmp_path / "book.txt"
book.write_text("Sentence one. " * 400, encoding="utf-8")
read = _read_aloud(chat, book, tmp_path / "bookmarks.json")
done = threading.Event()
def run():
adapter._stream(read)
done.set()
threading.Thread(target=run, daemon=True).start()
deadline = time.time() + 3
while adapter.daemon.pending_sends() < 3 and time.time() < deadline:
time.sleep(0.01)
time.sleep(0.1)
assert adapter.daemon.pending_sends() == 3, "the stream must not outrun the queue"
assert not done.is_set(), "the stream waits while the queue is full"
adapter._deliver({"source_hash": chat}, "stop")
assert done.wait(timeout=2), "a stop releases the waiting stream"
assert adapter._read_key is None
def test_service_marks_streamable_sources(tmp_path):
from semif_agent.gateway.lxmf import LxmfAdapter
scheduler = build_scheduler(tmp_path)
chat = "ab" * 16
adapter = LxmfAdapter(
{"allow_all_users": True, "voice": {"enabled": True}},
synthesizer=FakeSynthesizer(),
)
service = GatewayService(scheduler, adapter, config={})
assert scheduler.speech.supports(f"lxmf:{chat}") is False
adapter._mark_voice_chat(chat)
assert scheduler.speech.supports(f"lxmf:{chat}") is True
# A read registered for that chat is routed to the adapter's outbound queue.
scheduler.speech.read_aloud(
path="/books/f.txt",
key="k",
bookmarks_path="/books/bookmarks.json",
run_id="r1",
source=f"lxmf:{chat}",
)
service._owners["r1"] = ("lxmf", chat)
service.surface()
message = service.outbound["lxmf"].get_nowait()
assert message.stream is not None
assert message.stream.key == "k"
def test_service_marks_voice_gateway_streamable(tmp_path):
scheduler = build_scheduler(tmp_path)
GatewayService(scheduler, FakeStreamAdapter(), config={})
assert scheduler.speech.supports("voice:c") is True
# ---- service: multiple platforms ---- # ---- service: multiple platforms ----
class FakeLxmfAdapter: class FakeLxmfAdapter:
@@ -928,3 +1152,51 @@ def test_service_reply_routes_to_owning_platform(tmp_path):
) )
assert not service.outbound["lxmf"].empty() assert not service.outbound["lxmf"].empty()
assert service.outbound["simplex"].empty() assert service.outbound["simplex"].empty()
# ---- service: read-aloud streams route to a streaming front end ------------
class FakeStreamAdapter:
name = "voice"
supports_speech_stream = True
def test_service_routes_read_aloud_to_streaming_adapter(tmp_path):
scheduler = build_scheduler(tmp_path)
service = GatewayService(scheduler, FakeStreamAdapter(), config={})
scheduler.speech.read_aloud(
path="/books/p.txt",
key="gutenberg-1342",
bookmarks_path="/books/bookmarks.json",
run_id="r1",
source="voice:c",
title="Pride and Prejudice",
start=10,
)
service._owners["r1"] = ("voice", "c")
service.surface()
message = service.outbound["voice"].get_nowait()
assert message.stream is not None
assert message.stream.key == "gutenberg-1342"
assert message.stream.start == 10
assert message.text == ""
def test_service_skips_read_aloud_for_a_non_streaming_platform(tmp_path):
scheduler = build_scheduler(tmp_path)
service = build_service(scheduler) # FakeAdapter (simplex) cannot stream
scheduler.speech.read_aloud(
path="/books/p.txt",
key="gutenberg-1342",
bookmarks_path="/books/bookmarks.json",
run_id="r1",
source="simplex:4",
)
service._owners["r1"] = ("simplex", "4")
service.surface()
assert service.outbound["simplex"].empty()
assert any(
e["kind"] == "gateway_stream_unsupported" for e in scheduler.trace.read()
)
+336
View File
@@ -0,0 +1,336 @@
"""Pure-stdlib tests for the Ollama System One decision engine provider.
The engine is exercised over a real loopback HTTP server (the transport is not
mocked): the handler records requests and returns canned ollama
``/api/version``, ``/api/show``, and ``/v1/systemone`` responses, so the tests
prove the decision-contract mapping, the ollama-specific probing, and the strict
distribution validation. No model, no GGUF, no external network.
"""
from __future__ import annotations
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.engine import EngineUnavailable
from semif_agent.ollama_systemone import OllamaSystemOneConfig, OllamaSystemOneEngine
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *args): # keep the test output quiet
pass
def _read(self) -> dict:
length = int(self.headers.get("content-length", 0) or 0)
raw = self.rfile.read(length) if length else b"{}"
return json.loads(raw or b"{}")
def _send(self, status: int, payload: dict) -> None:
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
self.server.state.setdefault("gets", []).append(self.path)
if self.path == "/api/version":
self._send(
self.server.state.get("version_status", 200),
{"version": "0.40.13"},
)
else:
self._send(404, {"error": "not found"})
def do_POST(self):
body = self._read()
self.server.state.setdefault("requests", []).append(
(self.path, body, {k.lower(): v for k, v in self.headers.items()})
)
if self.path == "/api/show":
status = self.server.state.get("show_status", 200)
response = self.server.state.get("show_response")
if response is None:
response = _default_show()
self._send(status, response)
elif self.path == "/v1/systemone":
status = self.server.state.get("systemone_status", 200)
response = self.server.state.get("systemone_response")
if response is None:
response = _default_systemone(body)
self._send(status, response)
else:
self._send(404, {"error": "not found"})
def _default_show() -> dict:
return {
"model": "clef-flash",
"parameters": "num_ctx 16384",
"capabilities": ["decision"],
"model_info": {"clef.context_length": 262144},
}
def _default_systemone(body: dict) -> dict:
criteria = body["questions"]["decision"]["criteria"]
keys = list(criteria)
probs = {
key: (0.9 if index == 0 else 0.1 / max(len(keys) - 1, 1))
for index, key in enumerate(keys)
}
# Return the keys in REVERSE order to prove the engine aligns by id, not by
# position in the returned object.
return {
"model": "clef-flash",
"answers": {
"decision": {
"type": "choice",
"choice": keys[0],
"probabilities": dict(reversed(list(probs.items()))),
"confidence": 0.8,
}
},
"usage": {"input_tokens": 42, "output_tokens": 1},
}
@pytest.fixture()
def ollama():
server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
server.state = {}
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base = f"http://127.0.0.1:{server.server_address[1]}"
yield server, base
server.shutdown()
server.server_close()
def _engine(base: str, **cfg) -> OllamaSystemOneEngine:
return OllamaSystemOneEngine(
OllamaSystemOneConfig(base_url=base, model="clef-flash", timeout=5.0, **cfg)
)
def _decision(*option_ids: str) -> DecisionRequest:
return DecisionRequest(
state="the user said hello",
question="Which category handles this request?",
options=[Option(oid, f"description for {oid}") for oid in option_ids],
)
def test_call_maps_decision_to_a_choice_question(ollama):
server, base = ollama
result = _engine(base).call(_decision("response", "calendar"))
assert result.option_ids == ["response", "calendar"]
assert result.prob("response") == pytest.approx(0.9)
assert result.prob("calendar") == pytest.approx(0.1)
assert result.selected == "response"
assert result.extra["input_tokens"] == 42
assert result.extra["choice"] == "response"
assert result.extra["confidence"] == 0.8
assert result.extra["served_model"] == "clef-flash"
path, body, _ = server.state["requests"][-1]
assert path == "/v1/systemone"
assert body["model"] == "clef-flash"
assert body["state"] == "the user said hello"
question = body["questions"]["decision"]
assert question["type"] == "choice"
assert question["instructions"] == "Which category handles this request?"
assert question["criteria"] == {
"response": "description for response",
"calendar": "description for calendar",
}
# keep_alive is omitted unless configured.
assert "keep_alive" not in body
def test_call_sends_a_configured_keep_alive(ollama):
server, base = ollama
_engine(base, keep_alive="5m").call(_decision("a", "b"))
_, body, _ = server.state["requests"][-1]
assert body["keep_alive"] == "5m"
def test_call_sends_null_for_a_bare_label(ollama):
server, base = ollama
request = DecisionRequest(
state="state",
question="question",
options=[Option("a", ""), Option("b", " ")],
)
_engine(base).call(request)
_, body, _ = server.state["requests"][-1]
assert body["questions"]["decision"]["criteria"] == {"a": None, "b": None}
def test_call_normalizes_an_unnormalized_distribution(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {"decision": {"type": "choice", "probabilities": {"a": 0.4, "b": 0.4}}}
}
result = _engine(base).call(_decision("a", "b"))
assert result.probs == pytest.approx({"a": 0.5, "b": 0.5})
def test_call_rejects_mismatched_probability_keys(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {"decision": {"type": "choice", "probabilities": {"a": 1.0}}}
}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_a_choice_outside_the_requested_options(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {
"decision": {
"type": "choice",
"choice": "other",
"probabilities": {"a": 0.8, "b": 0.2},
}
}
}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_all_zero_distribution(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {"decision": {"type": "choice", "probabilities": {"a": 0.0, "b": 0.0}}}
}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_out_of_range_probability(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {"decision": {"type": "choice", "probabilities": {"a": 1.5, "b": 0.5}}}
}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_http_error_with_the_ollama_error_body(ollama):
server, base = ollama
server.state["systemone_status"] = 400
with pytest.raises(EngineUnavailable, match="400"):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_missing_answer(ollama):
server, base = ollama
server.state["systemone_response"] = {"answers": {}}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_requires_at_least_two_options(ollama):
_, base = ollama
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a"))
def test_call_requires_a_non_empty_state(ollama):
_, base = ollama
request = DecisionRequest(
state=" ",
question="q",
options=[Option("a", "a"), Option("b", "b")],
)
with pytest.raises(EngineUnavailable):
_engine(base).call(request)
def test_call_sends_bearer_token(ollama):
server, base = ollama
_engine(base, api_key="secret").call(_decision("a", "b"))
_, _, headers = server.state["requests"][-1]
assert headers.get("authorization") == "Bearer secret"
def test_generate_is_unavailable(ollama):
_, base = ollama
with pytest.raises(EngineUnavailable):
_engine(base).generate([{"role": "user", "content": "hi"}])
def test_warm_probes_ollama_native_endpoints_and_marks_loaded(ollama):
server, base = ollama
engine = _engine(base, context_tokens=0)
assert engine.loaded is False
engine.warm()
assert engine.loaded is True
assert "/api/version" in server.state["gets"]
assert [path for path, _, _ in server.state["requests"]] == ["/api/show"]
# context_tokens=0 follows the model's real num_ctx from /api/show.
assert engine.context_tokens == 16384
def test_warm_falls_back_to_the_architecture_context_length(ollama):
server, base = ollama
server.state["show_response"] = {
"capabilities": ["decision"],
"parameters": "",
"model_info": {"clef.context_length": 8192},
}
engine = _engine(base, context_tokens=0)
engine.warm()
assert engine.context_tokens == 8192
def test_warm_keeps_an_explicit_context_window(ollama):
server, base = ollama
engine = _engine(base, context_tokens=4096)
engine.warm()
assert engine.context_tokens == 4096
def test_warm_rejects_a_model_without_the_decision_capability(ollama):
server, base = ollama
server.state["show_response"] = {
"capabilities": ["completion", "thinking"],
"parameters": "num_ctx 4096",
}
with pytest.raises(EngineUnavailable, match="decision"):
_engine(base).warm()
def test_warm_rejects_a_missing_model(ollama):
server, base = ollama
server.state["show_status"] = 404
with pytest.raises(EngineUnavailable):
_engine(base).warm()
def test_warm_rejects_an_unreachable_server():
engine = OllamaSystemOneEngine(
OllamaSystemOneConfig(
base_url="http://127.0.0.1:1", model="clef-flash", timeout=1.0
)
)
with pytest.raises(EngineUnavailable):
engine.warm()
def test_unreachable_endpoint_raises_engine_unavailable():
engine = OllamaSystemOneEngine(
OllamaSystemOneConfig(
base_url="http://127.0.0.1:1", model="clef-flash", timeout=1.0
)
)
with pytest.raises(EngineUnavailable):
engine.call(_decision("a", "b"))
+144
View File
@@ -0,0 +1,144 @@
"""Pure-stdlib tests for the reading helpers and the scheduler speech channel.
`semif_agent.reading` owns bookmark persistence and deterministic speakable
chunking; `semif_agent.speech` owns the queue a skill posts a read-aloud request
to. Neither touches audio, the scheduler, or a gateway.
"""
import json
from semif_agent.reading import (
BOOKMARKS_FILE,
bookmarks_file,
chunk_text,
load_bookmarks,
read_offset,
save_bookmark,
)
from semif_agent.speech import ReadAloud, SpeechService
# ---- chunking --------------------------------------------------------------
def test_chunk_text_splits_and_offsets_are_contiguous():
text = "One. Two. Three. Four. Five. Six."
chunks = list(chunk_text(text, 0, 12))
assert len(chunks) > 1
for offset, chunk in chunks:
assert text[offset : offset + len(chunk)] == chunk
# The concatenation (whitespace-insensitive) is the original text.
assert "".join(chunk for _o, chunk in chunks).replace(" ", "") == text.replace(" ", "")
def test_chunk_text_resumes_deterministically_from_a_saved_offset():
text = "Alpha beta gamma. Delta epsilon zeta. Eta theta iota. Kappa lambda mu."
chunks = list(chunk_text(text, 0, 20))
assert len(chunks) >= 3
resume_offset = chunks[2][0]
# Resuming from a chunk boundary reproduces the tail exactly.
tail = list(chunk_text(text, resume_offset, 20))
assert tail == chunks[2:]
def test_chunk_text_respects_max_chars_without_a_good_break():
text = "x" * 100
chunks = list(chunk_text(text, 0, 30))
assert [len(chunk) for _o, chunk in chunks] == [30, 30, 30, 10]
def test_chunk_text_prefers_a_paragraph_break():
text = "A" * 40 + "\n\n" + "B" * 40
chunks = list(chunk_text(text, 0, 60))
# The first chunk ends at the paragraph break, not mid-word.
assert chunks[0][1] == "A" * 40
def test_chunk_text_empty_and_start_past_end():
assert list(chunk_text("", 0, 10)) == []
assert list(chunk_text("short", 999, 10)) == []
def test_chunk_text_skips_leading_whitespace_at_resume():
text = " hello world"
chunks = list(chunk_text(text, 0, 50))
assert chunks == [(2, "hello world")]
# ---- bookmarks -------------------------------------------------------------
def test_bookmarks_file_lives_in_the_books_directory(tmp_path):
assert bookmarks_file(tmp_path) == tmp_path / BOOKMARKS_FILE
def test_save_and_read_bookmark_roundtrip(tmp_path):
path = bookmarks_file(tmp_path)
assert read_offset(path, "gutenberg-1342") == 0
save_bookmark(path, "gutenberg-1342", 1234, "Pride and Prejudice")
assert read_offset(path, "gutenberg-1342") == 1234
entry = load_bookmarks(path)["gutenberg-1342"]
assert entry["offset"] == 1234
assert entry["title"] == "Pride and Prejudice"
assert "updated_at" in entry
# A second save keeps the other keys.
save_bookmark(path, "gutenberg-84", 7, "Frankenstein")
assert read_offset(path, "gutenberg-1342") == 1234
assert read_offset(path, "gutenberg-84") == 7
def test_save_bookmark_leaves_no_temp_file(tmp_path):
path = bookmarks_file(tmp_path)
save_bookmark(path, "k", 5)
assert not (tmp_path / (BOOKMARKS_FILE + ".tmp")).exists()
def test_bookmark_tolerates_missing_and_malformed(tmp_path):
path = bookmarks_file(tmp_path)
assert load_bookmarks(path) == {}
path.write_text("{not json")
assert load_bookmarks(path) == {}
assert read_offset(path, "k") == 0
# A legacy bare-integer entry is still read.
path.write_text(json.dumps({"k": 42}))
assert read_offset(path, "k") == 42
# A non-dict top level is ignored.
path.write_text(json.dumps([1, 2, 3]))
assert load_bookmarks(path) == {}
# ---- speech service --------------------------------------------------------
def test_speech_service_queues_and_drains():
service = SpeechService()
service.read_aloud(
path="/books/x.txt",
key="gutenberg-1",
bookmarks_path="/books/bookmarks.json",
run_id="r1",
source="voice:mic",
title="X",
start=10,
)
assert len(service.pending()) == 1
reads = service.drain()
assert len(reads) == 1
read = reads[0]
assert isinstance(read, ReadAloud)
assert read.key == "gutenberg-1"
assert read.start == 10
assert read.run_id == "r1"
# Drained once; the queue is empty afterwards.
assert service.drain() == []
assert service.pending() == []
def test_speech_service_is_bounded():
service = SpeechService(max_pending=2)
for index in range(5):
service.read_aloud(
path=f"/b/{index}.txt", key=str(index), bookmarks_path="/b/bookmarks.json"
)
assert len(service.pending()) == 2 # oldest dropped
assert [r.key for r in service.drain()] == ["3", "4"]
+17
View File
@@ -152,6 +152,23 @@ def test_maximum_config_enables_everything():
assert "llm_api_key" not in secrets assert "llm_api_key" not in secrets
def test_ollama_engine_answers_emit_the_ollama_block():
answers = Answers(
engine_provider="ollama",
ollama_base_url="http://10.0.0.9:11434",
ollama_model="clef-flash",
ollama_api_key="ok",
)
config = build_config(answers, _packs())
assert config["engine"]["provider"] == "ollama"
assert config["engine"]["ollama"]["base_url"] == "http://10.0.0.9:11434"
assert config["engine"]["ollama"]["model"] == "clef-flash"
assert config["engine"]["ollama"]["api_key"] == "!secret engine_ollama_api_key"
assert validate_config(config, _packs()) == []
assert build_plan(answers, _packs())["install_engine"] is False
assert build_secrets(answers)["engine_ollama_api_key"] == "ok"
def test_simplex_gateway_without_pack_still_needs_the_binary(): def test_simplex_gateway_without_pack_still_needs_the_binary():
answers = Answers(gateways=["simplex"]) answers = Answers(gateways=["simplex"])
plan = build_plan(answers, _packs()) plan = build_plan(answers, _packs())
+29
View File
@@ -223,6 +223,35 @@ def test_scheduler_exposes_a_read_only_catalog(tmp_path):
assert house_ctx.admin is scheduler assert house_ctx.admin is scheduler
assert plain_ctx.admin is None assert plain_ctx.admin is None
assert plain_ctx.catalog is scheduler.catalog assert plain_ctx.catalog is scheduler.catalog
# The scheduler's speech channel rides on every run context (a skill can
# post a long-form read-aloud for a voice front end).
assert plain_ctx.speech is scheduler.speech
def test_a_run_that_registers_a_read_is_terminal(tmp_path):
"""A run that hands off to a long-form read is the answer: a `continue`
assessment must not re-dispatch it (which authored a spurious skill)."""
scheduler = _scheduler(
tmp_path, choices={"additional work to be done": "continue"}
)
def act(ctx, request):
ctx.speech.read_aloud(
path="/b/x.txt",
key="k",
bookmarks_path="/b/bookmarks.json",
run_id=request.id,
source=request.source,
)
return ActionResult(action_log="Reading X aloud.", new_state="ok")
skill = Skill(name="read_book", category="books", description="Read.", act=act)
scheduler.tree.setdefault("books", []).append(skill)
result = scheduler._run_skill(skill, Request("read x", source="voice:c"))
assert result.intermediate is False, "a read-registering run must not continue"
kinds = [entry["kind"] for entry in scheduler.trace.read()]
assert "read_aloud_terminal" in kinds
assert "continued" not in kinds
def test_fidelity_gate_state_is_whole_body_without_the_request(tmp_path): def test_fidelity_gate_state_is_whole_body_without_the_request(tmp_path):
+388 -3
View File
@@ -10,7 +10,8 @@ non-`b"SIL"` frame speech, and the fake STT returns a fixed string.
""" """
from semif_agent.cli import _build_gateway_adapter, _resolve_platforms from semif_agent.cli import _build_gateway_adapter, _resolve_platforms
from semif_agent.gateway.voice import VoiceAdapter from semif_agent.gateway.base import OutboundMessage
from semif_agent.gateway.voice import VoiceAdapter, _is_stop_command
from semif_agent.voice_transport import VoiceDaemon, VoiceEngines from semif_agent.voice_transport import VoiceDaemon, VoiceEngines
@@ -26,6 +27,9 @@ class FakeAudio:
self.writes = [] self.writes = []
self.closed = False self.closed = False
self.input_opens = 0 self.input_opens = 0
#: Optional hook run at the start of `play` (to simulate a barge-in
#: landing mid-playback by setting the `stop_event`).
self.on_play = None
def open_input(self, sample_rate, frame_ms, device=""): def open_input(self, sample_rate, frame_ms, device=""):
self.input_opens += 1 self.input_opens += 1
@@ -41,6 +45,14 @@ class FakeAudio:
def write(self, pcm16, sample_rate): def write(self, pcm16, sample_rate):
self.writes.append((pcm16, sample_rate)) self.writes.append((pcm16, sample_rate))
def play(self, pcm16, sample_rate, stop_event=None):
if self.on_play is not None:
self.on_play(stop_event)
if stop_event is not None and stop_event.is_set():
return False
self.writes.append((pcm16, sample_rate))
return True
def flush(self): def flush(self):
pass # the scripted `frames` are input, not a capture buffer pass # the scripted `frames` are input, not a capture buffer
@@ -327,8 +339,12 @@ def test_watchdog_disabled_uses_blocking_read(monkeypatch):
# ---- half-duplex / speaking ------------------------------------------------ # ---- half-duplex / speaking ------------------------------------------------
def test_frames_ignored_while_speaking(): def test_frames_ignored_while_speaking_when_barge_in_disabled():
daemon, engines = make_daemon([b"WAKE", b"speech", b"SIL"]) # Strict half-duplex: with barge-in off the wake word is not even scored
# while a reply is playing, so the agent never transcribes its own voice.
daemon, engines = make_daemon(
[b"WAKE", b"speech", b"SIL"], config={"barge_in": {"enabled": False}}
)
daemon._speaking.set() daemon._speaking.set()
heard = [] heard = []
daemon.run(heard.append) daemon.run(heard.append)
@@ -336,6 +352,83 @@ def test_frames_ignored_while_speaking():
assert engines.stt.calls == [] assert engines.stt.calls == []
def test_barge_in_wake_aborts_playback_and_captures_command():
# A reply is playing; the wake word fires over it -> the daemon stops the
# playback, tells the front end (on_barge_in True then False), and captures
# the command that follows.
daemon, engines = make_daemon([b"WAKE", b"command", b"SIL", b"SIL"])
events = []
daemon._event = lambda kind, **kw: events.append(kind)
barges = []
def on_barge(active):
barges.append(active)
if active:
daemon._speaking.clear() # the interrupted playback has stopped
daemon.on_barge_in = on_barge
daemon._speaking.set() # a reply is playing when the wake word lands
heard = []
daemon.run(heard.append)
assert heard == ["hello"]
assert barges == [True, False]
assert "voice_barge_in" in events
assert "voice_wake" not in events # barge-in, not a fresh wake
def test_barge_in_threshold_gates_interruption():
# A barge-in threshold above the wake score means the reply is not
# interrupted (the agent's own TTS cannot self-trigger a barge-in).
daemon, engines = make_daemon(
[b"WAKE", b"command", b"SIL", b"SIL"],
config={"barge_in": {"threshold": 2.0}}, # FakeWake scores 1.0
)
daemon._speaking.set()
heard = []
daemon.run(heard.append)
assert heard == []
assert engines.stt.calls == []
def test_barge_in_without_command_releases_mute():
# The wake word interrupts, but no command follows: the listening session
# ends and the mute is lifted (the front end is not left muted).
daemon, engines = make_daemon([b"WAKE", b"SIL", b"SIL", b"SIL"])
daemon._speaking.set()
def on_barge(active):
if active:
daemon._speaking.clear()
daemon.on_barge_in = on_barge
daemon.run(lambda text: None)
assert daemon._mute.is_set() is False
def test_speak_muted_while_barge_in():
daemon, engines = make_daemon([])
events = []
daemon._event = lambda kind, **kw: events.append(kind)
daemon.set_muted(True)
daemon.speak("should not be spoken")
assert engines.tts.spoken == []
assert engines.audio.writes == []
assert "voice_speak_suppressed" in events
def test_speak_interrupted_mid_playback():
daemon, engines = make_daemon([])
events = []
daemon._event = lambda kind, **kw: events.append(kind)
def on_play(stop_event):
stop_event.set() # a barge-in lands while the buffer is playing
engines.audio.on_play = on_play
daemon.speak("a long reply")
assert "voice_speak_interrupted" in events
def test_speak_synthesizes_and_plays(): def test_speak_synthesizes_and_plays():
daemon, engines = make_daemon([]) daemon, engines = make_daemon([])
daemon.speak(" hello there ") daemon.speak(" hello there ")
@@ -438,6 +531,95 @@ def test_adapter_is_result_only():
assert VoiceAdapter({}).result_only is True assert VoiceAdapter({}).result_only is True
# ---- barge-in (adapter classification) -------------------------------------
def test_is_stop_command():
assert _is_stop_command("Stop.") is True
assert _is_stop_command("cancel") is True
assert _is_stop_command("stop please") is True
assert _is_stop_command("shut up already") is True
assert _is_stop_command(" Quiet! ") is True
assert _is_stop_command("never mind") is True
# A longer utterance is a real command, not a stop.
assert _is_stop_command("stop the timer") is False
assert _is_stop_command("shut the door") is False
assert _is_stop_command("turn on the lights") is False
assert _is_stop_command("") is False
def test_adapter_barge_in_stop_drops_replies_and_does_not_forward():
import queue
adapter = VoiceAdapter({})
seen = []
adapter._on_inbound = seen.append
outbound: "queue.Queue" = queue.Queue()
outbound.put(OutboundMessage("voice", "one"))
outbound.put(OutboundMessage("voice", "two"))
adapter._outbound = outbound
events = []
adapter.daemon._event = lambda kind, **kw: events.append(kind)
adapter.daemon.set_muted(True)
adapter._barged_in = True
adapter._on_utterance("stop")
adapter._handle(adapter._inbound.get())
assert seen == [] # never submitted as a request
assert outbound.empty() # the queued replies were dropped
assert "gateway_barge_in_stop" in events
assert "gateway_speech_dropped" in events
assert adapter.daemon._mute.is_set() is False # unmuted for later replies
def test_adapter_barge_in_stop_preserves_shutdown_sentinel():
import queue
adapter = VoiceAdapter({})
adapter._on_inbound = lambda message: None
outbound: "queue.Queue" = queue.Queue()
outbound.put(OutboundMessage("voice", "stale"))
outbound.put(None)
adapter._outbound = outbound
adapter._barged_in = True
adapter._on_utterance("cancel")
adapter._handle(adapter._inbound.get())
# The stale reply is dropped but the pump's sentinel is preserved.
assert outbound.get() is None
def test_adapter_barge_in_new_command_is_forwarded():
adapter = VoiceAdapter({})
seen = []
adapter._on_inbound = seen.append
adapter.daemon.set_muted(True)
adapter._barged_in = True
adapter._on_utterance("turn on the lights")
message = adapter._inbound.get()
assert message.raw.get("barge_in") is True
adapter._handle(message)
assert [m.text for m in seen] == ["turn on the lights"]
assert adapter.daemon._mute.is_set() is False
def test_adapter_normal_utterance_is_not_a_barge_in():
adapter = VoiceAdapter({})
seen = []
adapter._on_inbound = seen.append
adapter._on_utterance("hello")
message = adapter._inbound.get()
assert message.raw.get("barge_in") is not True
adapter._handle(message)
assert [m.text for m in seen] == ["hello"]
def test_adapter_on_barge_in_callback_sets_flag():
adapter = VoiceAdapter({})
adapter._on_barge_in(True)
assert adapter._barged_in is True
adapter._on_barge_in(False)
assert adapter._barged_in is False
# ---- CLI wiring ------------------------------------------------------------ # ---- CLI wiring ------------------------------------------------------------
@@ -745,3 +927,206 @@ def test_download_wake_file_rejects_sha_mismatch(tmp_path):
with pytest.raises(SystemExit): with pytest.raises(SystemExit):
module.download_wake_file("hey_computer", ref, wake_dir) module.download_wake_file("hey_computer", ref, wake_dir)
assert not (wake_dir / "hey_computer.onnx").exists() assert not (wake_dir / "hey_computer.onnx").exists()
# ---- read-aloud (long-form streaming) --------------------------------------
class FakeReadDaemon:
"""A daemon double for the read-aloud loop: records events and speech."""
def __init__(self, on_speak=None, max_speak_chars=600):
self.events = []
self.spoken = []
self._muted = False
self._stopping = False
self.on_speak = on_speak
self.max_speak_chars = max_speak_chars
def _event(self, kind, **fields):
self.events.append((kind, fields))
def speak(self, text):
self.spoken.append(text)
if self.on_speak is not None:
self.on_speak(self, text)
def set_muted(self, muted):
self._muted = muted
def muted(self):
return self._muted
def stopping(self):
return self._stopping
def stop(self):
self._stopping = True
def _adapter_with_daemon(on_speak=None, config=None):
adapter = VoiceAdapter(config or {})
daemon = FakeReadDaemon(on_speak=on_speak)
adapter.daemon = daemon
return adapter, daemon
def _book(tmp_path, text):
path = tmp_path / "book.txt"
path.write_text(text, encoding="utf-8")
return path
def _read(path, bookmarks, key="gutenberg-1", start=0, title="T"):
from semif_agent.speech import ReadAloud
return ReadAloud(
path=str(path),
key=key,
bookmarks_path=str(bookmarks),
start=start,
title=title,
)
def test_adapter_streams_chunks_and_records_completion(tmp_path):
from semif_agent.reading import read_offset
text = "One two three. " * 60
book = _book(tmp_path, text)
bookmarks = tmp_path / "bookmarks.json"
adapter, daemon = _adapter_with_daemon()
adapter._stream(_read(book, bookmarks))
assert len(daemon.spoken) > 1, "the text must be spoken in chunks"
assert all(chunk.strip() for chunk in daemon.spoken)
kinds = [kind for kind, _ in daemon.events]
assert "gateway_read_start" in kinds
assert "gateway_read_done" in kinds
# Finished: the bookmark sits at the end so a later request starts over.
assert read_offset(bookmarks, "gutenberg-1") == len(text)
assert adapter._read_active() is False
def test_adapter_stream_resumes_from_a_saved_offset(tmp_path):
from semif_agent.reading import read_offset, save_bookmark
text = "Sentence one. Sentence two. Sentence three. Sentence four."
book = _book(tmp_path, text)
bookmarks = tmp_path / "bookmarks.json"
save_bookmark(bookmarks, "gutenberg-1", 14, "T") # start of "Sentence two."
adapter, daemon = _adapter_with_daemon()
adapter._stream(_read(book, bookmarks, start=14))
spoken = " ".join(daemon.spoken)
assert spoken.startswith("Sentence two")
assert "Sentence one" not in spoken
assert read_offset(bookmarks, "gutenberg-1") == len(text)
def test_adapter_stream_stops_on_a_stop_signal(tmp_path):
from semif_agent.reading import read_offset
text = "Alpha beta gamma delta. " * 80
book = _book(tmp_path, text)
bookmarks = tmp_path / "bookmarks.json"
def on_speak(daemon, _text):
if len(daemon.spoken) == 2:
adapter._stop_reading("stop")
adapter, daemon = _adapter_with_daemon(on_speak=on_speak)
adapter._stream(_read(book, bookmarks))
assert len(daemon.spoken) == 2, "the read must stop at the next boundary"
kinds = [kind for kind, _ in daemon.events]
assert "gateway_read_stop" in kinds
assert "gateway_read_interrupted" in kinds
offset = read_offset(bookmarks, "gutenberg-1")
assert 0 < offset < len(text), "the interrupted chunk's start is the resume point"
assert adapter._read_active() is False
def test_adapter_stream_stops_when_a_barge_in_mutes(tmp_path):
text = "Alpha. Beta. Gamma. Delta. Epsilon. Zeta."
book = _book(tmp_path, text)
bookmarks = tmp_path / "bookmarks.json"
def on_speak(daemon, _text):
if len(daemon.spoken) == 1:
daemon.set_muted(True) # a barge-in landed during the first chunk
adapter, daemon = _adapter_with_daemon(on_speak=on_speak)
adapter._stream(_read(book, bookmarks))
assert len(daemon.spoken) == 1
assert adapter._read_active() is False
def test_adapter_stream_missing_file_is_traced_not_raised(tmp_path):
adapter, daemon = _adapter_with_daemon()
read = _read(tmp_path / "nope.txt", tmp_path / "bookmarks.json")
adapter._stream(read) # must not raise
assert daemon.spoken == []
assert any(kind == "gateway_read_failed" for kind, _ in daemon.events)
assert adapter._read_active() is False
def test_adapter_stream_chunks_never_exceed_the_speakable_budget(tmp_path):
# A chunk larger than the daemon's `max_speak_chars` would be truncated and
# lose text, so the stream clamps its chunk size below that budget.
text = "word " * 200
book = _book(tmp_path, text)
bookmarks = tmp_path / "bookmarks.json"
adapter, daemon = _adapter_with_daemon(config={"read": {"chunk_chars": 500}})
daemon.max_speak_chars = 40
adapter._stream(_read(book, bookmarks))
assert daemon.spoken
assert max(len(chunk) for chunk in daemon.spoken) <= 40
def test_adapter_supports_speech_stream_by_default_and_can_disable():
assert VoiceAdapter({}).supports_speech_stream is True
assert VoiceAdapter({"read": {"enabled": False}}).supports_speech_stream is False
def test_adapter_handle_stop_command_ends_the_read_without_forwarding(tmp_path):
import queue
text = "Alpha. Beta. Gamma. Delta."
book = _book(tmp_path, text)
adapter, daemon = _adapter_with_daemon()
adapter._on_inbound = lambda message: None
adapter._outbound = queue.Queue()
# Mark a read active (as the pump would while streaming).
with adapter._read_lock:
adapter._read_key = "gutenberg-1"
adapter._on_utterance("stop")
adapter._handle(adapter._inbound.get())
assert adapter._read_stop.is_set(), "the active read must be asked to stop"
assert daemon._muted is False # a normal stop never mutes
def test_adapter_handle_new_command_stops_the_read_and_forwards():
adapter, _daemon = _adapter_with_daemon()
seen = []
adapter._on_inbound = seen.append
with adapter._read_lock:
adapter._read_key = "gutenberg-1"
adapter._on_utterance("turn on the lights")
adapter._handle(adapter._inbound.get())
assert adapter._read_stop.is_set(), "a new command interrupts the read"
assert [m.text for m in seen] == ["turn on the lights"]
def test_adapter_barge_in_stop_also_ends_the_read():
adapter, _daemon = _adapter_with_daemon()
seen = []
adapter._on_inbound = seen.append
adapter._barged_in = True
with adapter._read_lock:
adapter._read_key = "gutenberg-1"
adapter._on_utterance("stop")
adapter._handle(adapter._inbound.get())
assert adapter._read_stop.is_set(), "a barge-in stop ends the read"
assert seen == []