Compare commits

...
8 Commits
Author SHA1 Message Date
gabby fc0beb5798 simplex: mark the reported message read so next_message advances
The bridge only read the daemon's unread state (/_get chats, /_get chat);
nothing wrote the read state, so a persistent-unread message was re-reported
on every call and simplex.next_message never advanced.

v7.0.3 does expose /_read chat @<id> and /_read chat items @<id> <ids>
(the earlier "v7 has no mark-read command" note was wrong). Added:

- SimplexDaemon.mark_read / request_mark_read plus read_command /
  parse_read_response; parse_direct_text_item now carries item_id.
- SimpleX bridge POST /read {"contact","item_ids"} marks exactly the listed
  items read on the bridge's own daemon, reporting ok/error honestly.
- The live inbox entry keeps item_id so /inbox/next hands back the
  consumable id.
- simplex.next_message consumes exactly the item it reported (a failed
  consume is surfaced as an honest note, never a fabricated read failure).

Precise per-item reading leaves the rest of the chat unread.
2026-10-09 11:16:21 +00:00
gabby 4e3e3f767c add previous skill result to semif context for successive requeues 2026-10-09 10:25:57 +00:00
gabby f05e06e6f6 normalize string outputs from time skills 2026-10-09 10:10:21 +00:00
gabby f6ef66b532 voice: tolerate the wake-tail pause; harden the front end
Endpointing fix. The wake detector usually fires inside the wake phrase,
so the first speech captured after it is the phrase's tail (plus the cue
beep echoing back through the mic), not the command. A fixed 500 ms
trailing-silence endpoint then ended the capture during the natural pause
before the command: the utterance held 240-400 ms of speech and STT
returned empty. In a recorded session 18 of 30 wakes dropped the command
that way (only 10 transcribed).

The endpoint now uses a longer silence tolerance (vad.initial_silence_ms,
default 1500) until vad.min_command_ms (default 700) of speech is in
hand, then reverts to vad.silence_ms, so a pause before the command is
tolerated while a real command still ends promptly.

Front-end hardening (the ways it was silently dying or losing work):

- Utterances run on a worker thread, not the audio thread, and a task
  error is traced and spoken rather than propagated, so one bad command
  cannot stop the mic or take the front end down.
- Capture-stream watchdog: read with a timeout and close/reopen the input
  after a sustained stall, so a wedged PortAudio/ALSA callback recovers
  instead of hanging the gateway (traced voice_stream_stalled/reopened).
- faulthandler enabled (CLI + unit) so a fatal signal dumps every
  thread's stack to the journal.
- The scheduler's answer-side entry points (answer, answer_question,
  resolve_repair, answer_approval) are guarded like submit_request: an
  EngineUnavailable is fatal-and-reported and any other resume/repair
  error returns a reply instead of propagating into a front end.
2026-10-09 09:41:00 +00:00
gabby e86ed805ee tests: stop flagging a literal 'the box' as a deployment leak
The machine-descriptor rule matched the Harvard-sentence recording
prompts (scripts/voice-prompts-en.txt: "The box was thrown beside the
parked truck."), where 'the box' is a literal box, not a colloquial dev
machine. Drop the bare phrase; keep the explicit dev/staging markers that
are never generic English.
2026-10-09 09:40:56 +00:00
gabby dcfe5e5fec audio: baseline the internal speaker at full volume on boot and hotplug
PortAudio has no volume control, so a muted ALSA Master silences the voice
gateway's cue and replies, and the mixer resets whenever a sound device is
added/removed. scripts/audio-baseline.sh sets the analog speaker (found by its
'Speaker' control, so a shifting card index does not matter) to 100% unmuted;
scripts/audio-baseline-watch.sh re-applies it on every sound udev event. Both
are driven by systemd user services (audio-baseline.service / -watch.service)
so they run at startup and on hotplug.
2026-10-09 08:19:39 +00:00
gabby ec39a990e4 voice: default wake word to "Hey Computer", capture command after a pause
openWakeWord ships no "computer" model, so pin a community
openWakeWord-compatible ONNX (Apache-2.0, sha256 in pins.json `wake_word`) and
fetch it into .runtime/voice/wake from scripts/voice-models.py. Its scores run
lower than the official models (~0.26-0.82 on the phrase, <0.02 on negatives),
so the seeded wake.threshold is 0.2 (the official models score ~0.99 at 0.5).

Also fix command capture: after the wake word the daemon now waits
listen_timeout_s (default 3s) for the command's speech to begin instead of
assuming it is glued to the wake word, so a natural pause while the cue beep
plays no longer truncates the command.
2026-10-09 08:19:36 +00:00
gabby ae37abbc3f debug tasklist 2026-10-09 02:28:46 +00:00
29 changed files with 1255 additions and 126 deletions

No files matched your search

+50 -24
View File
@@ -132,7 +132,9 @@ skill.py loop: observe -> act -> observe -> assess; the body is a single
summary is deterministic (no generation), built from
category.skill + ok/failed + action_log — the body writes only the
result, the runner adds the `category.name:` ref; the assess state carries
the resolved inputs (secrets redacted); a `DETERMINISTIC_CATEGORIES`
the skill's declared action, the goal, and the resolved inputs
(secrets redacted), and the requeue state flags a retry that would
reproduce the identical observed result as a no-op; a `DETERMINISTIC_CATEGORIES`
run (housekeeping) skips assessment/repair — it is an internal
mechanical action with a known result, not an external run;
a run paused for input is resumed by re-invoking act with the
@@ -1149,8 +1151,22 @@ CLI, unit tests (24) + integration tests (2).
so physical access is the authorization; a single configured `chat_id`
identifies the session and `home_channel` defaults to it so background
notifications (timers, repair offers) are spoken too. `run(on_inbound,
outbound)` starts an outbound-pump thread (`OutboundMessage` → `speak`) and
blocks in the mic loop. **Half-duplex**: capture frames are discarded while a
outbound)` starts an outbound-pump thread (`OutboundMessage` → `speak`) and an
**inbound-worker thread**, and blocks in the mic loop. Utterances are handed to
the worker, not run on the audio thread: the scheduler is synchronous and can
block on the decision engine, so a slow task must not stop the mic being read,
and the worker traces + speaks a task error instead of letting it kill the
front end. **Capture-stream watchdog**: `_read_frame` reads with
`audio.read_timeout_s`; when the stream stalls continuously for
`audio.stall_timeout_s` (a wedged PortAudio/ALSA callback that never delivers
another frame) it traces `voice_stream_stalled` and closes/reopens the input
(`voice_stream_reopened`), so the loop recovers instead of blocking forever.
**Endpointing tolerates the wake tail**: the wake detector can fire inside the
wake phrase and the cue beep follows, so the first speech captured is the
phrase's tail, not the command — until `vad.min_command_ms` of speech is in
hand the trailing-silence endpoint uses `vad.initial_silence_ms`, so a natural
pause before the command does not end the capture (then `vad.silence_ms`).
**Half-duplex**: capture frames are discarded while a
reply is speaking, so the agent never transcribes itself (no barge-in yet);
after a reply a `follow_up_window_s` accepts the next utterance without the
wake word, so answering a question is conversational. `max_speak_chars`
@@ -1180,7 +1196,10 @@ CLI, unit tests (24) + integration tests (2).
ownership across an updated request so its completion still routes home. A
`needs_input` pause sets `pending_owner` from the pending run's source; the
same chat's next message goes straight to `Scheduler.answer` (no
queue/navigation). A *different* chat — **including a chat on another
queue/navigation). The answer-side entry points (`answer`, `answer_question`,
`resolve_repair`, `answer_approval`) are guarded like `submit_request`: an
`EngineUnavailable` is fatal-and-reported and any other error returns a reply,
so a resume/repair failure never propagates into a front end. A *different* chat — **including a chat on another
platform** — during that pause is told to wait: the single-slot scheduler must
not silently abandon the first chat's run, and one service fronts all
adapters so the guard spans them. A background poll calls
@@ -1297,22 +1316,25 @@ CLI, unit tests (24) + integration tests (2).
localhost-bound, optional shared-secret `X-Semif-Token` header. `SimplexBridge`
buffers **every** inbound DM (no allowlist — the user wants to see who reached
the bot through its invite link) in a bounded `MessagingInbox` that owns the
read cursor, and serves `GET /health`, `GET /contacts` (the daemon's contact
list, refreshed on (re)connect and on demand — best-effort, falling back to
the cached/inbound-learned set when the daemon is unavailable), `GET /inbox`
(peek), `GET /inbox/next?contact=<id>` (pop oldest), `GET /unread` (the
daemon's persistent unread chats via `/_get chats` + `ChatListQuery` unread
filter — `chatStats{unreadCount, minUnreadItemId}` plus each previewed
`meta.itemStatus`; read-only), `GET /history?contact=<id>&count=<n>` (recent
messages for one chat via `/_get chat @<id>`; read-only), `GET /address`
(show/create the forwarding bot's contact link; 503 when the daemon is not
connected, 502 when the lookup fails), and `POST /send`
`{"recipient","text"}` (resolves a numeric id or a known display name —
refreshing the daemon contact list once on a miss — and enqueues on the
bridge's own daemon). `/unread` and `/history` read the daemon's own state
(surviving bridge restarts), unlike the live `/inbox` buffer; both are
read-only because v7 has no mark-read command (acking is a client-side read
receipt).
read cursor (each buffered entry keeps the daemon `item_id` so a consumer can
consume exactly that item), and serves `GET /health`, `GET /contacts` (the
daemon's contact list, refreshed on (re)connect and on demand — best-effort,
falling back to the cached/inbound-learned set when the daemon is unavailable),
`GET /inbox` (peek), `GET /inbox/next?contact=<id>` (pop oldest), `GET /unread`
(the daemon's persistent unread chats via `/_get chats` + `ChatListQuery`
unread filter — `chatStats{unreadCount, minUnreadItemId}` plus each previewed
`meta.itemStatus`), `GET /history?contact=<id>&count=<n>` (recent messages for
one chat via `/_get chat @<id>`), `GET /address` (show/create the forwarding
bot's contact link; 503 when the daemon is not connected, 502 when the lookup
fails), `POST /send` `{"recipient","text"}` (resolves a numeric id or a known
display name — refreshing the daemon contact list once on a miss — and
enqueues on the bridge's own daemon), and `POST /read` `{"contact","item_ids"}`
(marks exactly the listed received items read on the daemon via `/_read chat
items @<id> <ids>`, so they leave its persistent unread state; `ok` only when
the daemon accepted it). `/unread` and `/history` read the daemon's own state
(surviving bridge restarts), unlike the live `/inbox` buffer; `/read` is a real
local write on the bridge's own profile (v7 `/_read chat` updates the local
`item_status` only; no wire read receipt).
- **Skill-facing config.** A body calls a bridge at the address derived from that
bridge's own `bridges.<name>` block (`host`/`port`/`token`) — the
`simplex_bridge_url` / `llm_bridge_url` / `nextcloud_bridge_url` var (+ `_token`)
@@ -1424,10 +1446,14 @@ covered. Deferred follow-ups:
count)` / `request_chat_history()` query `/_get chat @<id> count=<n>` and
parse `apiChat`. `SimplexBridge` exposes `GET /unread` (persistent unread
chats, summaries + previewed messages) and `GET /history?contact=<id>&count=<n>`
(recent messages with per-item status), both read-only and degrading like
`/address` (503 not connected / 502 lookup failure; `/history` 400 without a
contact). The live `/inbox` buffer is unchanged. Note: v7 has **no mark-read
command**, so acking is via read receipts, not an API call.
(recent messages with per-item status), degrading like `/address` (503 not
connected / 502 lookup failure; `/history` 400 without a contact), plus
`POST /read` `{"contact","item_ids"}` which marks exactly the listed items read
on the daemon (`/_read chat items @<id> <ids>`), so a reported message is
consumed and not re-reported. The live `/inbox` buffer is unchanged. (The
pinned v7.0.3 **does** have `/_read chat @<id>`, `/_read chat items @<id>
<ids>`, and `/_read user <uid>`; an earlier note claiming v7 had no mark-read
command was wrong.)
- [x] **3. `simplex.send_message` seed** (`seeds/simplex/send_message/`). The
outbound counterpart to `simplex.next_message`: resolves the recipient with a
SemIf sub-decision over the bridge's `/contacts` (falling back to the
+16 -5
View File
@@ -667,18 +667,29 @@ python -m semif_agent.cli gateway --platform voice
PortAudio has no volume control — use `alsamixer`/`amixer` (then
`sudo alsactl store`) to unmute and set the mic/speaker levels.
- **Models.** `gateway.voice.wake.model` is an openWakeWord model (default
`hey_mycroft`), `stt.model` a faster-whisper size (default `base.en`), and
`hey_computer`, spoken phrase "Hey Computer"), `stt.model` a faster-whisper
size (default `base.en`), and
`tts.voice` a Piper voice (default `en_US-lessac-medium`). Bootstrap downloads
the openWakeWord models into the venv's package dir (under `.runtime/venv`)
and the Piper voice into `.runtime/voice/tts`; the faster-whisper model lands
in the `.runtime/hf` cache.
the official openWakeWord models into the venv's package dir (under
`.runtime/venv`) and the Piper voice into `.runtime/voice/tts`; the
faster-whisper model lands in the `.runtime/hf` cache. openWakeWord ships no
"computer" model, so the default is a **pinned community model**
(openWakeWord-compatible, sha256-checked in `pins.json`) that
`scripts/voice-models.py` fetches into `.runtime/voice/wake`, where the
detector resolves it via `wake.model_dir`. Set `wake.model` to an official
name (e.g. `alexa`) or a path to switch. Because the community model's scores
run lower than the official models, the seeded `wake.threshold` is `0.2` (the
official models score ~0.99 and use `0.5`).
- **Behavior.** Half-duplex — capture is discarded while a reply is speaking, so
the agent never transcribes itself (no barge-in yet). A short beep plays when
the wake word fires (`gateway.voice.cue`), so you know you're being heard; set
`cue.submit_frequency > 0` for a second beep once the utterance is
transcribed. After a reply, the next
utterance is accepted **without** the wake word for `follow_up_window_s`, so
answering a question is conversational. `max_speak_chars` truncates long
answering a question is conversational. After the wake word, capture waits
`listen_timeout_s` for the command to begin, so a pause before speaking
(e.g. while the cue beep plays) does not truncate it. `max_speak_chars`
truncates long
replies before speaking. `result_only` (default true for voice) speaks only the
skill's result line — scheduler bookkeeping is dropped and the
`<skill>: ok —` wrapper is stripped — so the spoken output is the answer, not
+12 -4
View File
@@ -217,7 +217,7 @@
"text_batch_delay": 0.8
},
"voice": {
"_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (bootstrap downloads models into the venv, where they resolve by name; model_dir is an optional local dir for a custom model file); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After each reply the next utterance is accepted without the wake word for follow_up_window_s. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `<skill>: ok —` wrapper) instead of the full scheduler output; set false for the complete text. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too.",
"_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (official models download into the venv and resolve by name; a pinned community model such as the default 'hey_computer' is fetched into model_dir, .runtime/voice/wake); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After each reply the next utterance is accepted without the wake word for follow_up_window_s. After the wake word, listen_timeout_s is how long to wait for the command to start before giving up, so a pause before speaking does not truncate it. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `<skill>: ok —` wrapper) instead of the full scheduler output; set false for the complete text. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too. A stalled capture stream (the PortAudio callback stops delivering frames) is detected via audio.read_timeout_s and recovered by closing and reopening the input after audio.stall_timeout_s, so the front end no longer hangs silently. Utterances run on a worker thread (not the audio thread), so a slow or failing task neither stops the mic being read nor kills the front end.",
"enabled": false,
"chat_id": "voice",
"display_name": "voice",
@@ -226,6 +226,7 @@
"result_only": true,
"max_speak_chars": 600,
"follow_up_window_s": 5.0,
"listen_timeout_s": 3.0,
"cue": {
"_comment": "Audible feedback. A short sine beep plays when the wake word fires so you know you're being heard; set submit_frequency > 0 for a second beep once the utterance is transcribed. volume is 0..1.",
"enabled": true,
@@ -236,8 +237,9 @@
"submit_duration_ms": 100
},
"wake": {
"model": "hey_mycroft",
"threshold": 0.5,
"_comment": "model is an openWakeWord name/path. The default 'hey_computer' is a pinned community model whose scores run lower than the official models (measured ~0.26-0.82 on the phrase, <0.02 on negatives), so threshold 0.2 is tuned for it; the official models (e.g. hey_mycroft) score ~0.99 and are fine at 0.5.",
"model": "hey_computer",
"threshold": 0.2,
"inference_framework": "onnx",
"model_dir": ""
},
@@ -255,18 +257,24 @@
"volume": 1.0
},
"audio": {
"_comment": "Capture-stream watchdog: read_timeout_s is how long a frame read waits before it counts as a stall; when the stream stalls continuously for stall_timeout_s (a wedged PortAudio/ALSA callback stops delivering frames) the input is closed and reopened so the voice front end recovers instead of hanging forever. 0 for either restores the old blocking read with no recovery.",
"input_device": "",
"output_device": "",
"sample_rate": 16000,
"frame_ms": 80,
"capture_sample_rate": 0,
"output_sample_rate": 0,
"dc_removal": true
"dc_removal": true,
"read_timeout_s": 1.0,
"stall_timeout_s": 5.0
},
"vad": {
"_comment": "Endpointing. silence_ms is the trailing-silence endpoint once a command is underway. The wake detector can fire inside the wake phrase (and the cue beep follows), so the first speech captured is the phrase's tail, not the command: until min_command_ms of speech is in hand the endpoint uses initial_silence_ms instead, so a natural pause before the command does not end the capture. min_speech_ms rejects a blip; max_utterance_s caps a runaway.",
"silence_ms": 500,
"min_speech_ms": 120,
"max_utterance_s": 30,
"min_command_ms": 700,
"initial_silence_ms": 1500,
"aggressiveness": 2,
"energy_threshold": 200.0
}
+8
View File
@@ -19,5 +19,13 @@
"piper_train_ref": "efffbfb226bfb511ebbcf55d0cecd8b35a89743d",
"base_checkpoint_url": "https://huggingface.co/datasets/rhasspy/piper-checkpoints/resolve/main/en/en_US/lessac/medium/epoch=2164-step=1355540.ckpt",
"base_checkpoint_sha256": "ab7e5b8dab40f834b7cc58ae4ad7b7009c954b901e4ddbb784bbe11ce379a1cd"
},
"wake_word": {
"_comment": "openWakeWord-compatible wake-word model refs fetched by scripts/voice-models.py into .runtime/voice/wake (deployment-independent, code-owned like the other pins). openWakeWord ships no 'computer' model, so this community-trained ONNX (Apache-2.0, same mel/embedding feature models) is pinned by sha256. 'phrase' is the spoken wake phrase.",
"hey_computer": {
"url": "https://huggingface.co/Soulcreek2/speechkit-wakeword-models/resolve/main/hey_computer.onnx",
"sha256": "3acbd9ffff04beba2d16ebdfd0d4c734d65fecdd22446f25f4d0afa6e5d7606b",
"phrase": "Hey Computer"
}
}
}
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# Re-apply the audio baseline whenever a sound device is added, changed, or
# removed, so the internal speaker stays at full volume and unmuted (the
# baseline) after a USB mic, HDMI, or headset is plugged or unplugged.
#
# `udevadm monitor` is readable without root, so this runs as a long-lived
# systemd user service (see `audio-baseline.service`); each sound event
# triggers one idempotent apply of `audio-baseline.sh`.
set -u
BASELINE="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)/audio-baseline.sh"
stdbuf -oL udevadm monitor --udev --subsystem-match=sound 2>/dev/null \
| while IFS= read -r line; do
# Event lines look like `UDEV [1696.123] add /devices/... (sound)`;
# the `[` distinguishes them from the 3-line startup banner.
case "$line" in
UDEV*\[*) "$BASELINE" ;;
esac
done
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# Restore the internal analog speaker to full volume, unmuted.
#
# PortAudio/ALSA has no volume control, so the voice gateway's cue beep and
# spoken replies are silent when the card's Master is muted or at 0%. The mixer
# also resets when a sound device is added or removed (e.g. a USB mic or HDMI
# unplug), so this runs both at startup and on every hotplug event (see
# `audio-baseline-watch.sh`).
#
# The card is identified by its 'Speaker' control (HDMI cards only expose
# IEC958), so a shifting card index after a device change does not matter.
# Idempotent and safe to run repeatedly; exits 0 when no card is present yet
# (the watcher retries on the next hotplug event).
set -u
for dir in /proc/asound/card*/; do
[ -e "$dir" ] || continue
idx=${dir#/proc/asound/card}
idx=${idx%/}
amixer -c "$idx" scontrols 2>/dev/null | grep -q "'Speaker'" || continue
amixer -c "$idx" sset Master 100% unmute >/dev/null 2>&1 || true
amixer -c "$idx" sset Speaker 100% unmute >/dev/null 2>&1 || true
amixer -c "$idx" sset Headphone 100% unmute >/dev/null 2>&1 || true
done
exit 0
+3 -3
View File
@@ -642,9 +642,9 @@ Voice command gateway (wake word + speech-to-text + text-to-speech):
Enable it in config.json with gateway.voice.enabled = true, then run it in
the foreground (it needs your audio session; it is NOT a systemd unit):
HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli gateway --platform voice
- Say the wake word (gateway.voice.wake.model, default 'hey_mycroft') and
speak; the reply is spoken back. After each reply the next utterance needs
no wake word for gateway.voice.follow_up_window_s.
- Say the wake word (gateway.voice.wake.model, default 'hey_computer' — phrase
"Hey Computer") and speak; the reply is spoken back. After each reply the
next utterance needs no wake word for gateway.voice.follow_up_window_s.
- If the mic or speaker is silent/quiet, set the ALSA mixer (PortAudio has no
volume control) and persist it:
alsamixer # or: amixer -c <card> sset 'Speaker' unmute
+3
View File
@@ -8,6 +8,9 @@ Type=simple
WorkingDirectory=@REPO@
Environment=HF_HOME=@REPO@/.runtime/hf
Environment=PYTHONUNBUFFERED=1
# Dump every thread's stack on a fatal signal so a wedged front end (e.g. the
# voice mic loop) leaves a trace in the journal instead of hanging silently.
Environment=PYTHONFAULTHANDLER=1
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform all
Restart=always
RestartSec=5
+58 -9
View File
@@ -6,9 +6,12 @@ Run after installing `requirements/voice.txt` (bootstrap does this with
`gateway.voice` from config.json so the downloaded models match the configured
names, or take explicit flags.
- **Wake word** (openWakeWord): downloaded by `openwakeword.utils.download_models`
into the venv's package resources dir (inside `.runtime/venv/`, so still
contained in the checkout). The detector resolves the model by name there.
- **Wake word** (openWakeWord): official models are downloaded by
`openwakeword.utils.download_models` into the venv's package resources dir
(inside `.runtime/venv/`, so still contained in the checkout); the detector
resolves the model by name there. A **pinned community model** (openWakeWord
ships no "computer" model) is fetched from `pins.json` `wake_word` into the
configured `model_dir` (`.runtime/voice/wake`) and verified by sha256.
- **TTS** (Piper): the voice `.onnx` + `.onnx.json` are fetched from the
`rhasspy/piper-voices` HF repo into `.runtime/voice/tts/`.
- **STT** (faster-whisper): instantiating the model warms it into the HF cache
@@ -18,12 +21,15 @@ names, or take explicit flags.
from __future__ import annotations
import argparse
import hashlib
import json
import shutil
import urllib.request
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
RUNTIME = REPO_ROOT / ".runtime" / "voice"
PINS = REPO_ROOT / "pins.json"
PIPER_REPO = "rhasspy/piper-voices"
@@ -42,15 +48,56 @@ def piper_hf_path(voice: str) -> str:
return f"{lang}/{locale}/{name}/{quality}/{voice}.onnx"
def download_wake(name: str) -> None:
def pinned_wake_models() -> dict:
"""Return the code-owned wake-word refs from `pins.json` (`name` -> ref)."""
try:
pins = json.loads(PINS.read_text())
except Exception:
return {}
block = pins.get("wake_word", {}) or {}
return {
name: ref
for name, ref in block.items()
if isinstance(ref, dict) and ref.get("url")
}
def _sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def download_wake_file(name: str, ref: dict, target_dir: Path) -> None:
"""Fetch a pinned community wake model into `target_dir`, verifying sha256."""
url = str(ref["url"])
expected = str(ref.get("sha256", "") or "")
target_dir.mkdir(parents=True, exist_ok=True)
dest = target_dir / f"{name}.onnx"
if dest.is_file() and (not expected or _sha256(dest) == expected):
print(f"== wake word: {dest.name} (present)")
return
print(f"== wake word: {url} -> {dest}")
with urllib.request.urlopen(url) as resp: # pinned https URL from pins.json
data = resp.read()
if expected and hashlib.sha256(data).hexdigest() != expected:
raise SystemExit(f"sha256 mismatch for {name}: refusing to write {dest}")
dest.write_bytes(data)
def download_wake(name: str, target_dir: Path) -> None:
import openwakeword.utils as utils
print(f"== wake word model: {name}")
# Default target: the venv's package resources dir (inside .runtime/venv).
# openWakeWord resolves the model (and its shared mel/embedding models) by
# name from there.
# Always fetch the shared feature (mel/embedding) + VAD models, and for an
# official name the phrase model itself, into the venv's package resources
# dir (inside .runtime/venv). An unknown name is skipped here.
utils.download_models(model_names=[name])
# A pinned community model (openWakeWord ships no "computer" model) is
# fetched into the configured model_dir so the detector resolves it by path.
ref = pinned_wake_models().get(name)
if ref:
download_wake_file(name, ref, target_dir)
def download_voice(voice: str, target: Path) -> None:
from huggingface_hub import hf_hub_download
@@ -86,6 +133,8 @@ def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", default=str(REPO_ROOT / "config.json"))
parser.add_argument("--wake", default=None, help="openWakeWord model name")
parser.add_argument("--wake-dir", default=str(RUNTIME / "wake"),
help="target dir for a pinned community wake model")
parser.add_argument("--stt", default=None, help="faster-whisper model size/path")
parser.add_argument("--tts", default=None, help="Piper voice id")
parser.add_argument("--tts-dir", default=str(RUNTIME / "tts"))
@@ -95,12 +144,12 @@ def main(argv: list[str] | None = None) -> int:
args = parser.parse_args(argv)
voice_cfg = _config_voice(Path(args.config))
wake = args.wake or (voice_cfg.get("wake", {}) or {}).get("model") or "hey_mycroft"
wake = args.wake or (voice_cfg.get("wake", {}) or {}).get("model") or "hey_computer"
stt = args.stt or (voice_cfg.get("stt", {}) or {}).get("model") or "base.en"
tts = args.tts or (voice_cfg.get("tts", {}) or {}).get("voice") or "en_US-lessac-medium"
if not args.skip_wake:
download_wake(wake)
download_wake(wake, Path(args.wake_dir))
if not args.skip_tts:
download_voice(tts, Path(args.tts_dir))
if not args.skip_stt:
+50 -5
View File
@@ -11,8 +11,9 @@ oldest unread message for that conversation.
When the live buffer is empty it falls back to the daemon's persistent unread
(`/unread` + `/history`), so a message that arrived before the bridge started is
still reported. (v7 has no mark-read command, so a persistent-unread message can
be reported again until the user reads it in their own client.)
still reported. After reporting a message, that single item is marked read on
the daemon through the bridge (`POST /read`), so the next call advances to the
next unread message instead of re-reporting the same one.
The bridge owns the read cursor, so this skill keeps no state of its own. It
never opens a WebSocket to the `simplex-chat` daemon — the bridge is the only
@@ -84,6 +85,41 @@ def _get(ctx, path):
raise BridgeError(f"GET {path}: {exc}") from exc
def _post(ctx, path, payload):
data = json.dumps(payload).encode("utf-8")
headers = {**_headers(ctx), "Content-Type": "application/json"}
request = urllib.request.Request(
_base(ctx) + path, data=data, headers=headers, method="POST"
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"POST {path}: {exc}") from exc
def _mark_read(ctx, contact, item_id):
"""Mark one just-reported item read via the bridge.
Returns None on success, or a short honest reason string on failure. The
message was still reported, so a failed consume is surfaced as a note rather
than fabricated into a read failure.
"""
item = str(item_id or "").strip()
if not item:
return None
try:
payload = _post(ctx, "/read", {"contact": contact, "item_ids": [item]})
except BridgeError as exc:
return str(exc)
if not payload.get("ok"):
return payload.get("error") or "the bridge did not mark it read"
return None
# ---- conversation resolution ----
@@ -189,7 +225,13 @@ def _read_live(ctx, request, senders):
new_state="no unread SimpleX messages",
decisions=decisions,
)
return _report(message.get("display_name") or contact, message.get("text"), decisions)
read_note = _mark_read(ctx, contact, message.get("item_id"))
return _report(
message.get("display_name") or contact,
message.get("text"),
decisions,
read_note,
)
def _read_persistent(ctx, request):
@@ -250,9 +292,12 @@ def _read_persistent(ctx, request):
sender = next(
(s["display_name"] for s in senders if s["id"] == str(contact)), str(contact)
)
return _report(sender, messages[0].get("text"), decisions)
read_note = _mark_read(ctx, contact, messages[0].get("item_id"))
return _report(sender, messages[0].get("text"), decisions, read_note)
def _report(sender, body, decisions):
def _report(sender, body, decisions, read_note=None):
report = f"SimpleX message from {sender}: {str(body or '')}"
if read_note:
report += f" (could not mark it read: {read_note})"
return ActionResult(action_log=report, new_state=report, decisions=decisions)
+51 -1
View File
@@ -55,6 +55,8 @@ class BridgeHandler(BaseHTTPRequestHandler):
history = {}
requests = []
tokens = []
read_calls = []
read_ok = True
def _send(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
@@ -88,11 +90,31 @@ class BridgeHandler(BaseHTTPRequestHandler):
else:
self._send({"error": "not found"}, 404)
def do_POST(self):
url = urllib.parse.urlparse(self.path)
length = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(length).decode("utf-8") or "{}")
if url.path != "/read":
self._send({"error": "not found"}, 404)
return
self.read_calls.append(payload)
if self.read_ok:
self._send(
{
"ok": True,
"contact_id": payload.get("contact"),
"item_ids": payload.get("item_ids"),
"status": "read",
}
)
else:
self._send({"ok": False, "error": "the daemon rejected the read"})
def log_message(self, *args):
pass
def start_server(messages, unread_chats=None, history=None):
def start_server(messages, unread_chats=None, history=None, read_ok=True):
handler = type(
"Handler",
(BridgeHandler,),
@@ -102,6 +124,8 @@ def start_server(messages, unread_chats=None, history=None):
"history": dict(history or {}),
"requests": [],
"tokens": [],
"read_calls": [],
"read_ok": read_ok,
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
@@ -112,6 +136,7 @@ def start_server(messages, unread_chats=None, history=None):
def message(identifier, contact, name, text):
return {
"id": identifier,
"item_id": str(identifier),
"contact_id": contact,
"display_name": name,
"text": text,
@@ -148,6 +173,9 @@ def test_multiple_senders_uses_semif_decision():
assert handler.requests[0] == "/inbox", handler.requests
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
assert [m["id"] for m in handler.messages] == ["m1"], "the popped message must be consumed"
assert handler.read_calls == [{"contact": "7", "item_ids": ["m2"]}], (
"the reported item must be marked read, and only it"
)
print(action.action_log)
finally:
server.shutdown()
@@ -226,6 +254,7 @@ def test_single_sender_needs_no_decision():
action = skill.act(ctx, request)
assert engine.decisions == []
assert "hi" in action.action_log, action.action_log
assert handler.read_calls == [{"contact": "4", "item_ids": ["m1"]}]
print(action.action_log)
finally:
server.shutdown()
@@ -279,6 +308,7 @@ def test_empty_live_inbox_falls_back_to_persistent_unread():
assert handler.requests == ["/inbox", "/unread", "/history?contact=3&count=50"], (
handler.requests
)
assert handler.read_calls == [{"contact": "3", "item_ids": ["8"]}]
print(action.action_log)
finally:
server.shutdown()
@@ -322,6 +352,7 @@ def test_persistent_unread_prefers_a_healthy_conversation():
assert handler.requests == ["/inbox", "/unread", "/history?contact=4&count=50"], (
handler.requests
)
assert handler.read_calls == [{"contact": "4", "item_ids": ["20"]}]
print(action.action_log)
finally:
server.shutdown()
@@ -353,6 +384,24 @@ def test_auth_token_is_sent_when_configured():
server.server_close()
def test_failed_read_marking_is_surfaced_honestly():
"""A message is still reported when consuming it fails, with an honest note
instead of a fabricated failure of the read."""
server, handler, url = start_server(
[message("m1", "4", "Alice", "hi")], read_ok=False
)
try:
ctx = ActionContext(engine=FakeEngine(), config=config(url))
action = skill.act(ctx, Request("read my next simplex message"))
assert "hi" in action.action_log, action.action_log
assert "could not mark it read" in action.action_log, action.action_log
assert handler.read_calls == [{"contact": "4", "item_ids": ["m1"]}]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_multiple_senders_uses_semif_decision()
test_strong_winner_overrides_default_contact()
@@ -364,6 +413,7 @@ def main():
test_persistent_unread_prefers_a_healthy_conversation()
test_unreachable_bridge_fails_honestly()
test_auth_token_is_sent_when_configured()
test_failed_read_marking_is_surfaced_honestly()
print("ok")
+1 -1
View File
@@ -17,5 +17,5 @@ CONTRACT = {}
def act(ctx, request):
today = local_now(ctx.config).date()
message = f"Today is {today.strftime('%A, %B %d, %Y')} ({today.isoformat()})."
message = f"Today is {today.strftime('%A, %B')} {today.day}, {today.year}."
return ActionResult(action_log=message, new_state=message)
+1 -14
View File
@@ -9,8 +9,6 @@ the machine itself.
from __future__ import annotations
from datetime import datetime
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
@@ -19,18 +17,7 @@ INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars":
CONTRACT = {}
def _offset_text(now: datetime) -> str:
offset = now.strftime("%z")
if not offset:
return ""
return f" UTC{offset[:3]}:{offset[3:]}"
def act(ctx, request):
now = local_now(ctx.config)
zone = now.tzname() or "local"
message = (
f"It is {now.strftime('%H:%M')} "
f"({now.strftime('%I:%M %p').lstrip('0')} {zone}{_offset_text(now)})."
)
message = f"It is {now.strftime('%I:%M %p').lstrip('0')}."
return ActionResult(action_log=message, new_state=message)
+4 -1
View File
@@ -2,7 +2,7 @@
The bridge owns the read cursor so a read skill stays stateless. Generic over
transports: entries are normalized message dicts (`contact_id`, `display_name`,
`text`), which is exactly what `semif_agent.simplex_ws` yields.
`text`, `item_id`), which is exactly what `semif_agent.simplex_ws` yields.
"""
from __future__ import annotations
@@ -28,6 +28,9 @@ class MessagingInbox:
"contact_id": contact_id,
"display_name": display_name,
"text": message.get("text") or "",
# The transport's per-item id (SimpleX `itemId`), when known: lets a
# consumer mark exactly this message read on the daemon.
"item_id": str(message.get("item_id") or ""),
"received_at": time.time(),
}
with self._lock:
+6 -11
View File
@@ -873,10 +873,10 @@ class OutlookClient:
# ---- To Do tasks ----
def list_task_lists(self) -> list[dict]:
items = self._paged(
"/me/todo/lists",
{"$select": "id,displayName,isOwner,wellknownListName", "$top": 100},
)
# No $select: Graph's To Do endpoints reject OData $select for personal
# (consumer) Microsoft accounts with RequestBroker--ParseUri, while $top
# is accepted. Fetch the full shape and read the fields we need.
items = self._paged("/me/todo/lists", {"$top": 100})
return [
{
"id": item.get("id"),
@@ -905,14 +905,9 @@ class OutlookClient:
def list_tasks(self, task_list="") -> list[dict]:
list_id = self._resolve_task_list(task_list)
# No $select here either: see list_task_lists (consumer To Do quirk).
items = self._paged(
f"/me/todo/lists/{urllib.parse.quote(list_id)}/tasks",
{
"$select": (
"id,title,status,importance,dueDateTime,completedDateTime,body,createdDateTime"
),
"$top": 100,
},
f"/me/todo/lists/{urllib.parse.quote(list_id)}/tasks", {"$top": 100}
)
return [_task(item, list_id) for item in items]
+66
View File
@@ -80,6 +80,13 @@ class SimplexBridge(BridgeService):
"sndSent/sndRcvd, and a failed send (e.g. an auth error on a dead "
"connection) returns ok:false with the reason — never a false "
"success. 400 on a missing/invalid field or an unknown recipient",
"POST /read {\"contact\": \"<id>\", \"item_ids\": [\"<id>\", ...]} -> "
"200 {\"ok\": bool, \"contact_id\": \"<id>\", \"item_ids\": [...], "
"\"status\": \"read|rejected|error|unavailable\", \"error\": "
"\"...\"?} — mark the given received items read on the daemon so they "
"leave its persistent unread state; only the listed ids are consumed. "
"`ok` is true only when the daemon accepted it — never a fabricated "
"success. 400 on a missing contact or empty item_ids",
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
"configured and the auth header is missing or wrong",
),
@@ -181,6 +188,8 @@ class SimplexBridge(BridgeService):
return 404, {"error": "not found"}
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
if path == "/read":
return self._read(payload)
if path != "/send":
return 404, {"error": "not found"}
recipient = payload.get("recipient")
@@ -197,6 +206,63 @@ class SimplexBridge(BridgeService):
# ---- actions ----
def _read(self, payload: dict) -> tuple[int, dict]:
contact = payload.get("contact")
item_ids = payload.get("item_ids")
if not isinstance(contact, str) or not contact.strip():
return 400, {"error": "contact is required"}
if not isinstance(item_ids, list) or not item_ids:
return 400, {"error": "item_ids is required"}
try:
result = self.mark_read(contact, item_ids)
except ValueError as exc:
return 400, {"error": str(exc)}
return 200, result
def mark_read(self, contact: str, item_ids) -> dict:
"""Mark the given received items read on the bridge's own daemon.
Returns `{ok, contact_id, item_ids, status, error?}`. `ok` is True only
when the daemon accepted the command; a disconnected or failing daemon
reports the reason (never a false success). Reading is precise: only the
listed item ids are consumed, so the rest of the chat stays unread.
"""
contact_id = str(contact or "").strip()
ids = [str(i).strip() for i in (item_ids or []) if str(i).strip()]
if not contact_id:
raise ValueError("contact is required")
if not ids:
raise ValueError("item_ids is required")
try:
response = self.daemon.request_mark_read(contact_id, ids)
except RuntimeError as exc:
return {
"ok": False,
"contact_id": contact_id,
"item_ids": ids,
"status": "unavailable",
"error": str(exc)[:300],
}
except Exception as exc: # TimeoutError, daemon error
return {
"ok": False,
"contact_id": contact_id,
"item_ids": ids,
"status": "error",
"error": str(exc)[:300],
}
ok = bool(response.get("ok")) if isinstance(response, dict) else False
result = {
"ok": ok,
"contact_id": contact_id,
"item_ids": ids,
"status": "read" if ok else "rejected",
}
if not ok:
detail = response.get("error") if isinstance(response, dict) else ""
result["error"] = detail or "the daemon did not mark the items read"
return result
def refresh_contacts(self) -> list[dict]:
"""Best-effort refresh of the daemon's contact list into the inbox.
+7
View File
@@ -13,6 +13,7 @@ Run on a host with SemIf + a GGUF + a local OpenAI-compatible server:
from __future__ import annotations
import argparse
import faulthandler
import json
import os
import sys
@@ -822,6 +823,12 @@ def run_gateway(
run two scheduler processes over one skill store), so each gets its own
transport thread but they route through one `GatewayService`.
"""
# Dump every thread's Python stack on a fatal signal (SIGSEGV/SIGABRT/...):
# a wedged front end (e.g. a voice loop stuck on the mic) leaves a trace in
# the journal instead of dying silently. Also enabled by the unit's
# PYTHONFAULTHANDLER=1; harmless when set twice.
faulthandler.enable()
gateway_cfg = config.get("gateway", {}) or {}
platforms = _resolve_platforms(platform, gateway_cfg)
+44 -10
View File
@@ -42,6 +42,11 @@ class VoiceAdapter(GatewayAdapter):
#: `run()` blocks on the mic; this daemon owns capture/wake/STT/TTS.
self.daemon = VoiceDaemon(cfg, trace=trace, name=self.name)
self._on_inbound = None
#: Utterances are handed to a worker thread, not run on the audio
#: thread: the scheduler is synchronous and can block on the decision
#: engine, and a slow or failing task must neither stop the mic being
#: read nor kill the front end. `None` asks the worker to stop.
self._inbound: "queue.Queue[InboundMessage | None]" = queue.Queue()
# ---- requirements ----
@@ -69,13 +74,42 @@ class VoiceAdapter(GatewayAdapter):
self.daemon.speak(message.text)
threading.Thread(target=_pump, name="voice-outbound-pump", daemon=True).start()
self.daemon.run(self._on_utterance)
threading.Thread(
target=self._inbound_worker, name="voice-inbound-worker", daemon=True
).start()
try:
self.daemon.run(self._on_utterance)
finally:
self._inbound.put(None)
def close(self) -> None:
self.daemon.close()
# ---- inbound ----
def _inbound_worker(self) -> None:
"""Run the scheduler off the audio thread, one utterance at a time.
The scheduler is synchronous and can block on the decision engine; a
slow task must not stop the mic being read, and a task error is traced
and spoken rather than propagated — one bad command must not take the
voice front end down with it.
"""
while True:
message = self._inbound.get()
if message is None:
return
self._handle(message)
def _handle(self, message: InboundMessage) -> None:
if self._on_inbound is None:
return
try:
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.")
def _on_utterance(self, text: str) -> None:
text = (text or "").strip()
if not text:
@@ -86,13 +120,13 @@ class VoiceAdapter(GatewayAdapter):
display_name=self.display_name,
chars=len(text),
)
message = InboundMessage(
text=text,
chat_id=self.chat_id,
chat_type="dm",
contact_id=self.chat_id,
display_name=self.display_name,
raw={},
self._inbound.put(
InboundMessage(
text=text,
chat_id=self.chat_id,
chat_type="dm",
contact_id=self.chat_id,
display_name=self.display_name,
raw={},
)
)
if self._on_inbound is not None:
self._on_inbound(message)
+47 -2
View File
@@ -631,7 +631,21 @@ class Scheduler:
a pre-act contract variable is left unset and marked skipped, and an
act-driven pause receives the empty string (the body may then fail,
which is assessed normally).
Guarded like `submit_request`: a front end calls this synchronously
(the voice adapter from its worker thread), so an engine failure must
be fatal-and-reported, and any other error must come back as a reply
rather than propagate and take the front end down.
"""
try:
return self._answer(text)
except EngineUnavailable as exc:
return SchedulerReply("fatal", self._mark_fatal(exc))
except Exception as exc:
self.trace.append("error", "?", phase="answer", message=str(exc))
return SchedulerReply("error", f"could not resume the run: {exc}")
def _answer(self, text: str) -> SchedulerReply:
with self._lock:
if self.pending is None:
return SchedulerReply("error", "no run is waiting for input")
@@ -699,6 +713,10 @@ class Scheduler:
requeued = False
if outcome.updated_request and request.reentries < self.max_reentries:
child = _requeue(request, outcome.updated_request)
# Remember what this attempt observed so the next assessment can
# tell a genuine retry (the result changed) from a guaranteed
# repeat against unchanged state.
child.meta["prev_result"] = outcome.action_log or outcome.new_state
self.queue.push(child)
self.trace.append("requeued", request.id, text=outcome.updated_request)
if self.on_request_requeued is not None:
@@ -818,8 +836,17 @@ class Scheduler:
"""Answer a deferred question. An empty answer skips it.
A repair question carries the detail the user wants the skill repaired
with; answering it starts the repair directly.
with; answering it starts the repair directly. Guarded so an engine or
repair failure is reported instead of propagating into the front end.
"""
try:
return self._answer_question(question_id, text)
except EngineUnavailable as exc:
return "fatal", self._mark_fatal(exc)
except Exception as exc:
return "error", f"could not record the answer: {exc}"
def _answer_question(self, question_id: str, text: str) -> tuple[str, str]:
offer_id: str | None = None
answer = (text or "").strip()
with self._lock:
@@ -870,7 +897,16 @@ class Scheduler:
The draft worker is blocked in `_request_approval`; setting the status
and notifying releases it (True registers + writes the body, False
aborts). The terminal trace event is written by the worker, not here.
Guarded so an unexpected failure is reported instead of propagating.
"""
try:
return self._answer_approval(approval_id, approved)
except EngineUnavailable as exc:
return "fatal", self._mark_fatal(exc)
except Exception as exc:
return "error", f"could not record the approval: {exc}"
def _answer_approval(self, approval_id: str, approved: bool) -> tuple[str, str]:
with self._lock:
approval = next(
(a for a in self.approvals if a.id == approval_id), None
@@ -915,8 +951,17 @@ class Scheduler:
`retry` requeues the original request; `repair_skill` rewrites the body
from the observed failure; `ask_user` posts a question whose answer
starts the repair; `no_repair` closes the offer. Repair writes are
bounded by `codegen.repair.max_attempts` per skill.
bounded by `codegen.repair.max_attempts` per skill. Guarded so a retry
run or write failure is reported instead of propagating.
"""
try:
return self._resolve_repair(offer_id, action)
except EngineUnavailable as exc:
return "fatal", self._mark_fatal(exc)
except Exception as exc:
return "error", f"could not execute the repair: {exc}"
def _resolve_repair(self, offer_id: str, action: str | None = None) -> tuple[str, str]:
with self._lock:
offer = next((r for r in self.repairs if r.id == offer_id), None)
if offer is None:
+77 -4
View File
@@ -186,10 +186,10 @@ def parse_chat(achat: dict) -> dict | None:
def parse_direct_text_item(item: dict) -> InboundDict | None:
"""Normalize one `newChatItems` entry into a message dict, or None.
Returns `{text, contact_id, display_name, raw}` for a received direct text
message. Drops group chats, own echoes, non-text content, and items with no
resolvable contact id. Authorization is the caller's job — this layer is
deliberately policy-free.
Returns `{text, contact_id, display_name, item_id, raw}` for a received
direct text message. Drops group chats, own echoes, non-text content, and
items with no resolvable contact id. Authorization is the caller's job —
this layer is deliberately policy-free.
"""
chat_info = item.get("chatInfo") or {}
if chat_info.get("type") != "direct":
@@ -221,11 +221,15 @@ def parse_direct_text_item(item: dict) -> InboundDict | None:
entry = contact_entry(contact)
if entry is None:
return None
item_id = (chat_item.get("meta") or {}).get("itemId")
return {
"text": text,
"contact_id": entry["id"],
"display_name": entry["display_name"],
"local_name": entry.get("local_name", ""),
# Carried so a consumer can mark exactly this item read (the bridge's
# live inbox keeps it; the command gateway ignores it).
"item_id": str(item_id) if item_id is not None else "",
"raw": item,
}
@@ -281,6 +285,39 @@ def parse_send_response(resp: dict) -> dict:
return {"item_id": None, "status": "", "error": "daemon returned no message id"}
def read_command(chat_id: str, item_ids=None) -> str:
"""Structured command that marks a chat, or specific items, read.
v7 exposes `/_read chat @<id>` (the whole chat) and `/_read chat items @<id>
<comma-separated item ids>` (a precise subset). The item form is used so
consuming the next unread message clears exactly that message and leaves the
rest of the chat untouched. With no usable item ids it falls back to the
whole-chat form.
"""
chat_ref = f"@{str(chat_id).strip().lstrip('@')}"
if item_ids:
ids = ",".join(str(i).strip() for i in item_ids if str(i).strip())
if ids:
return f"/_read chat items {chat_ref} {ids}"
return f"/_read chat {chat_ref}"
def parse_read_response(resp: dict) -> dict:
"""Normalize a `/_read chat` response into `{ok, type, error}`.
A successful item read comes back as `itemsReadForChat` and a whole-chat
read as the chat's `ok`; a rejected command comes back as `chatCmdError`.
`ok` is True only when the daemon did not report an error, so a caller never
treats a rejected (or empty) response as a consumed message.
"""
if not isinstance(resp, dict) or not resp:
return {"ok": False, "type": "", "error": "empty daemon response"}
if resp.get("type") == "chatCmdError" or resp.get("error"):
detail = resp.get("chatError") or resp.get("error") or "read command failed"
return {"ok": False, "type": "chatCmdError", "error": str(detail)[:300]}
return {"ok": True, "type": resp.get("type") or "", "error": ""}
class SimplexDaemon:
"""One WebSocket connection to a `simplex-chat` daemon.
@@ -518,6 +555,42 @@ class SimplexDaemon:
future.cancel()
raise TimeoutError("simplex send request timed out") from exc
# ---- read ----
async def mark_read(
self, chat_id: str, item_ids=None, timeout: float = 20.0
) -> dict:
"""Mark a direct chat, or specific items, read on the daemon.
`/_read chat items @<id> <ids>` clears exactly the reported items'
`rcv_new` status (leaving other unread messages intact);
`/_read chat @<id>` clears the whole chat. Returns `{ok, type, error}`.
A transport failure raises (via `_roundtrip`) — never a fabricated
success.
"""
resp = await self._roundtrip(read_command(chat_id, item_ids), timeout)
return parse_read_response(resp)
def request_mark_read(
self, chat_id: str, item_ids=None, timeout: float = 20.0
) -> dict:
"""Thread-safe read-mark for callers off the event loop.
Raises `RuntimeError` when no live connection exists and `TimeoutError`
when the daemon does not answer in time — never a fabricated success.
"""
loop = self._loop
if loop is None or not loop.is_running():
raise RuntimeError("simplex gateway is not connected")
future = asyncio.run_coroutine_threadsafe(
self.mark_read(chat_id, item_ids, timeout=timeout), loop
)
try:
return future.result(timeout=timeout + 5.0)
except concurrent.futures.TimeoutError as exc:
future.cancel()
raise TimeoutError("simplex read request timed out") from exc
# ---- contacts ----
async def active_user(self, timeout: float = 20.0) -> int:
+22 -3
View File
@@ -295,15 +295,19 @@ class SkillRunner:
then offered to `assess:requeue`, which picks complete/retry. On retry
the original request text is re-dispatched (the scheduler bounds it by
`max_reentries`). Both are real logged decision rows. The state carries
the resolved inputs so a wrong resolution is visible to the decision.
The engine is always real: EngineUnavailable propagates to the
scheduler, which marks the app fatal.
the skill's declared action, the goal, and the resolved inputs so the
decision sees what the skill was meant to do and how its inputs
resolved; the requeue state additionally flags a retry that would
reproduce the identical observed result as a no-op. The engine is always
real: EngineUnavailable propagates to the scheduler, which marks the app
fatal.
"""
label = f"{skill.category}.{skill.name}"
resolved = _resolved_inputs(skill, ctx.config)
outcome = DecisionRequest(
state=(
f"skill: {label}\n"
f"skill action: {skill.description}\n"
f"goal: {request.text}\n"
f"resolved inputs:\n{resolved}\n"
f"action log:\n{action.action_log}"
@@ -334,13 +338,28 @@ class SkillRunner:
if success:
return True, None
# A retry that would reproduce the identical observed result is a
# guaranteed no-op run (the request, config, and external state are
# unchanged), so the requeue decision is told before it can pick
# `retry` again — otherwise a deterministic failure loops through the
# reentry ladder and ends in a repair offer for a working skill.
observed = action.action_log or action.new_state
prev = request.meta.get("prev_result")
no_progress = ""
if prev is not None and prev == observed:
no_progress = (
"\nAttempts so far produced the identical result; retrying "
"would repeat the same run against unchanged state."
)
requeue = DecisionRequest(
state=(
f"skill: {label}\n"
f"skill action: {skill.description}\n"
f"goal: {request.text}\n"
f"resolved inputs:\n{resolved}\n"
f"action log:\n{action.action_log}\n"
"outcome: failed"
f"{no_progress}"
),
question="Is the request complete, or should it run again?",
options=[
+140 -19
View File
@@ -103,15 +103,17 @@ class Synthesizer:
class AudioIO:
"""Mic capture and speaker playback.
`read()` blocks for one frame and returns its bytes, or `None` once the
input is closed (the loop exits on `None`). `open_output`/`write` may be
called at any sample rate the synthesizer produced.
`read(timeout)` returns one frame's bytes; with a `timeout` it returns
`b""` when no frame arrived in time, and `None` once the input is closed
(the loop exits on `None`). The timeout is how the loop detects a stalled
capture stream and recovers from it. `open_output`/`write` may be called at
any sample rate the synthesizer produced.
"""
def open_input(self, sample_rate: int, frame_ms: int, device: str = "") -> None:
raise NotImplementedError
def read(self) -> bytes | None:
def read(self, timeout: float | None = None) -> bytes | None:
raise NotImplementedError
def open_output(self, sample_rate: int, device: str = "") -> None:
@@ -442,8 +444,9 @@ class SoundDeviceAudio(AudioIO):
def read(self, timeout: float | None = None) -> bytes | None:
"""Block for the next frame (or up to `timeout` seconds).
Returns `None` once the input is closed, or on a `timeout` with no
frame — a caller that passes a timeout can detect a stalled stream
Returns `None` once the input is closed (the sentinel `close()` puts on
the queue), or `b""` when a `timeout` elapses with no frame — so a
caller that passes a timeout can detect a stalled capture stream
instead of blocking forever.
"""
if timeout is None:
@@ -451,7 +454,7 @@ class SoundDeviceAudio(AudioIO):
try:
return self._frames.get(timeout=timeout)
except queue.Empty:
return None
return b""
def open_output(self, sample_rate: int, device: str = "") -> None:
pass # a raw stream is opened per utterance in `write`
@@ -543,7 +546,7 @@ def build_engines(cfg: dict, trace=None) -> VoiceEngines:
audio_cfg = cfg.get("audio", {}) or {}
wake_model = resolve_model_path(
str(wake_cfg.get("model", "hey_mycroft") or ""),
str(wake_cfg.get("model", "hey_computer") or ""),
str(wake_cfg.get("model_dir", "") or ""),
(".onnx", ".tflite"),
)
@@ -555,7 +558,7 @@ def build_engines(cfg: dict, trace=None) -> VoiceEngines:
return VoiceEngines(
wake=OpenWakeWordDetector(
wake_model,
threshold=float(wake_cfg.get("threshold", 0.5)),
threshold=float(wake_cfg.get("threshold", 0.2)),
inference_framework=str(wake_cfg.get("inference_framework", "onnx")),
),
vad=_build_vad(cfg),
@@ -601,15 +604,37 @@ class VoiceDaemon:
self.config = cfg
self.trace = trace
self.name = name
self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.5))
self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.2))
#: After the wake word, how long to wait for the command's speech to
#: begin before giving up (a natural pause after "hey <word>" — e.g.
#: waiting for the cue beep — must not truncate the command).
self.listen_timeout_ms = int(float(cfg.get("listen_timeout_s", 3.0) or 0) * 1000)
audio_cfg = cfg.get("audio", {}) or {}
self.sample_rate = int(audio_cfg.get("sample_rate", SAMPLE_RATE) or SAMPLE_RATE)
self.frame_ms = int(audio_cfg.get("frame_ms", 80) or 80)
self.input_device = str(audio_cfg.get("input_device", "") or "")
#: Capture-stream watchdog. `read_timeout_s` is how long a frame read
#: waits before it counts as a stall; when the stream stalls
#: continuously for `stall_timeout_s` the input is closed and reopened
#: (a wedged PortAudio/ALSA callback otherwise blocks `read()` forever).
#: 0 for either restores the old blocking read with no recovery.
self.read_timeout_s = float(audio_cfg.get("read_timeout_s", 1.0) or 0.0)
self.stall_timeout_s = float(audio_cfg.get("stall_timeout_s", 5.0) or 0.0)
self._stall_since = 0.0
vad_cfg = cfg.get("vad", {}) or {}
self.vad_silence_ms = int(vad_cfg.get("silence_ms", 1000) or 1000)
self.min_speech_ms = int(vad_cfg.get("min_speech_ms", 120) or 120)
self.max_utterance_s = float(vad_cfg.get("max_utterance_s", 30) or 30)
#: A longer silence tolerance while the utterance is still short. The
#: wake detector can fire inside the wake phrase (the cue beep follows),
#: so the first speech after it is the phrase's tail, not the command;
#: a natural pause before the command must not end the capture. Once
#: `min_command_ms` of speech is in hand, the normal `vad_silence_ms`
#: endpoint applies (so a real command still ends promptly).
self.min_command_ms = int(vad_cfg.get("min_command_ms", 700) or 0)
self.initial_silence_ms = max(
int(vad_cfg.get("initial_silence_ms", 1500) or 0), self.vad_silence_ms
)
self.follow_up_window = float(cfg.get("follow_up_window_s", 5.0) or 0.0)
self.max_speak_chars = int(cfg.get("max_speak_chars", 600) or 0)
cue = cfg.get("cue", {}) or {}
@@ -694,12 +719,15 @@ class VoiceDaemon:
def _loop(self, engines: VoiceEngines) -> None:
while not self._stop.is_set():
pcm = engines.audio.read()
pcm = self._read_frame(engines)
if pcm is None:
return
if not pcm:
continue
if self._speaking.is_set():
continue
armed = time.time() < self._follow_until
wait_for_speech_ms = 0
if not armed:
score = engines.wake.score(pcm)
if score < self.wake_threshold:
@@ -710,8 +738,12 @@ class VoiceDaemon:
except Exception:
pass
self._cue(self.cue_frequency, self.cue_duration_ms)
# Wait for the command to start rather than assuming it is
# glued to the wake word (the wake frame + a natural pause are
# discarded so the command is not truncated).
wait_for_speech_ms = self.listen_timeout_ms
self._follow_until = 0.0
utterance = self._collect(engines, pcm)
utterance = self._collect(engines, pcm, wait_for_speech_ms=wait_for_speech_ms)
if not utterance:
continue
try:
@@ -728,31 +760,66 @@ class VoiceDaemon:
if self._on_utterance is not None:
self._on_utterance(text)
def _collect(self, engines: VoiceEngines, first_frame: bytes) -> bytes:
"""Accumulate frames from the wake word until trailing silence."""
frames = [first_frame]
speech_ms = self.frame_ms
def _collect(self, engines: VoiceEngines, first_frame: bytes, wait_for_speech_ms: int = 0) -> bytes:
"""Accumulate frames from the wake word until trailing silence.
With `wait_for_speech_ms > 0`, `first_frame` (the wake-word frame) and
any leading silence are discarded and capture starts only once the
command's speech begins — so a natural pause after the wake word does
not truncate the command. Gives up after that many milliseconds with no
speech (traced `voice_no_command`).
"""
frames: list[bytes] = []
speech_ms = 0
silence_ms = 0
started = time.time()
#: Wall-clock of the most recent frame the VAD called speech — the
#: "last word spoken" boundary the latency breakdown measures from.
last_speech_ts = started
waiting = wait_for_speech_ms > 0
wait_started = started
if not waiting:
frames.append(first_frame)
speech_ms = self.frame_ms
while not self._stop.is_set():
if self._speaking.is_set():
break # a reply started; stop capturing so we don't transcribe it
if self.max_utterance_s > 0 and (time.time() - started) >= self.max_utterance_s:
break
pcm = engines.audio.read()
pcm = self._read_frame(engines)
if pcm is None:
break
if not pcm:
# No frame within the read timeout: keep waiting, but still
# honor the "command never started" deadline below.
if waiting and (time.time() - wait_started) * 1000.0 >= wait_for_speech_ms:
self._event("voice_no_command", waited_ms=wait_for_speech_ms)
return b""
continue
is_speech = engines.vad.is_speech(pcm, self.sample_rate)
if waiting:
if not is_speech:
if (time.time() - wait_started) * 1000.0 >= wait_for_speech_ms:
self._event("voice_no_command", waited_ms=wait_for_speech_ms)
return b""
continue
waiting = False
frames.append(pcm)
if engines.vad.is_speech(pcm, self.sample_rate):
if is_speech:
speech_ms += self.frame_ms
silence_ms = 0
last_speech_ts = time.time()
else:
silence_ms += self.frame_ms
if silence_ms >= self.vad_silence_ms:
# Tolerate a longer pause until the command's speech is underway
# (see `initial_silence_ms`): the wake phrase's tail is captured
# first, and a pause before the actual command must not end it.
limit = (
self.initial_silence_ms
if speech_ms < self.min_command_ms
else self.vad_silence_ms
)
if silence_ms >= limit:
break
if speech_ms < self.min_speech_ms:
self._event(
@@ -766,6 +833,60 @@ class VoiceDaemon:
self._event("voice_utterance", frames=len(frames), speech_ms=speech_ms)
return b"".join(frames)
# ---- capture health ----
def _read_frame(self, engines: VoiceEngines) -> bytes | None:
"""Read one capture frame, recovering from a stalled stream.
Returns the frame bytes, `b""` when no frame arrived within
`read_timeout_s`, or `None` once the input is closed. When the stream
stalls continuously for `stall_timeout_s` — the PortAudio callback has
stopped delivering, so a blocking `read()` would hang the front end
forever — the input is closed and reopened so the loop recovers.
"""
timeout = self.read_timeout_s if self.read_timeout_s > 0 else None
pcm = engines.audio.read(timeout=timeout)
if pcm is None:
return None
if pcm:
self._stall_since = 0.0
return pcm
if timeout is None or self.stall_timeout_s <= 0:
return b""
now = time.time()
if not self._stall_since:
self._stall_since = now
return b""
if now - self._stall_since >= self.stall_timeout_s:
self._stall_since = 0.0
self._reopen_input(engines)
return b""
def _reopen_input(self, engines: VoiceEngines) -> None:
"""Close and reopen the capture stream after a stall (best-effort).
A stalled PortAudio/ALSA stream never delivers another frame, so the
blocking read would hang the whole front end. Reopening gives the
device a fresh stream; a hard failure is traced and backed off rather
than raised, so the loop keeps retrying instead of dying.
"""
self._event("voice_stream_stalled", stall_s=round(self.stall_timeout_s, 3))
try:
engines.audio.close()
except Exception:
pass
try:
engines.audio.open_input(self.sample_rate, self.frame_ms, self.input_device)
except Exception as exc:
self._event("voice_stream_reopen_failed", message=str(exc)[:200])
time.sleep(min(2.0, self.stall_timeout_s or 1.0))
return
try:
engines.wake.reset()
except Exception:
pass
self._event("voice_stream_reopened")
# ---- speaking ----
def _cue(self, frequency: float, duration_ms: int) -> None:
+38
View File
@@ -728,3 +728,41 @@ def test_empty_result_is_assessed_as_success(tmp_path):
assert "assess:requeue" not in phases, (
"an empty discovery must not be retried or repaired"
)
def test_read_result_is_assessed_as_success(tmp_path):
"""A correctly-read result is a successful run, not a failure.
The assessment must see the skill's declared action; with only the skill
label the real model marked a truthful read failed for ambiguous phrasings
(e.g. "What's my next simplex message?"), which then looped the retry ladder
and offered to repair a working skill. This exercises the real engine, since
only it produces the probabilities.
"""
config = load_config()
require_real(config)
engine = SemIfEngine(build_engine_config(config))
def act(ctx, request):
return ActionResult(
action_log="SimpleX message from pepper: hello",
new_state="SimpleX message from pepper: hello",
)
skill = Skill(
name="next_message",
category="simplex",
description="Read the next unread SimpleX message.",
act=act,
)
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
runner = SkillRunner(ActionContext(engine=engine, config={}), log)
outcome = runner.run(skill, Request("What's my next simplex message?"))
print(f"[{outcome.success}] {outcome.summary}")
assert outcome.success is True, outcome.summary
phases = [row["extra"]["phase"] for row in log.read()]
assert "assess:outcome" in phases
assert "assess:requeue" not in phases, (
"a truthful read must not be retried or repaired"
)
+91 -2
View File
@@ -38,6 +38,8 @@ class FakeDaemon:
history_error=None,
send_response=None,
send_error=None,
read_response=None,
read_error=None,
):
self.link = link
self.error = error
@@ -49,9 +51,12 @@ class FakeDaemon:
self.history_error = history_error
self.send_response = send_response
self.send_error = send_error
self.read_response = read_response
self.read_error = read_error
self.refresh_count = 0
self.chat_calls = []
self.history_calls = []
self.read_calls = []
self.sent = []
self.closed = False
self.on_message = None
@@ -105,6 +110,14 @@ class FakeDaemon:
raise self.history_error
return list(self.history_list)
def request_mark_read(self, chat_id, item_ids=None, timeout=20.0):
self.read_calls.append((str(chat_id), list(item_ids or [])))
if self.read_error is not None:
raise self.read_error
if self.read_response is not None:
return self.read_response
return {"ok": True, "type": "itemsReadForChat", "error": ""}
def close(self):
self.closed = True
@@ -116,8 +129,13 @@ def start_bridge(daemon=None, **config):
return bridge, daemon, f"http://127.0.0.1:{port}"
def inbound(text, contact_id="4", display_name="Alice"):
return {"text": text, "contact_id": contact_id, "display_name": display_name}
def inbound(text, contact_id="4", display_name="Alice", item_id=""):
return {
"text": text,
"contact_id": contact_id,
"display_name": display_name,
"item_id": item_id,
}
def get(url, token=None):
@@ -722,3 +740,74 @@ def test_describe_bridges_renders_service_auth_and_endpoints():
assert "/unread" in text
assert "/history" in text
assert "never speak" in text
def test_read_marks_given_items_only():
daemon = FakeDaemon()
bridge, _, base = start_bridge(daemon=daemon)
try:
result = post(f"{base}/read", {"contact": "4", "item_ids": ["8", "9"]})
assert result == {
"ok": True,
"contact_id": "4",
"item_ids": ["8", "9"],
"status": "read",
}
assert daemon.read_calls == [("4", ["8", "9"])], "only the listed items"
finally:
bridge.stop()
def test_read_validates_body():
bridge, daemon, base = start_bridge()
try:
payloads = (
{"item_ids": ["8"]},
{"contact": "4"},
{"contact": "4", "item_ids": []},
{"contact": " ", "item_ids": ["8"]},
)
for payload in payloads:
with pytest.raises(urllib.error.HTTPError) as exc:
post(f"{base}/read", payload)
assert exc.value.code == 400
assert daemon.read_calls == []
finally:
bridge.stop()
def test_read_without_connection_is_unavailable():
bridge, _, base = start_bridge(
daemon=FakeDaemon(read_error=RuntimeError("not connected"))
)
try:
result = post(f"{base}/read", {"contact": "4", "item_ids": ["8"]})
assert result["ok"] is False
assert result["status"] == "unavailable"
assert "not connected" in result["error"]
finally:
bridge.stop()
def test_read_reports_a_rejected_read():
bridge, _, base = start_bridge(
daemon=FakeDaemon(read_response={"ok": False, "error": "agent error"})
)
try:
result = post(f"{base}/read", {"contact": "4", "item_ids": ["8"]})
assert result["ok"] is False
assert result["status"] == "rejected"
assert result["error"] == "agent error"
finally:
bridge.stop()
def test_inbox_carries_item_id_for_consumption():
bridge, _, base = start_bridge()
try:
bridge._on_message(inbound("hi", contact_id="4", item_id="33"))
popped = get(f"{base}/inbox/next")["message"]
assert popped["item_id"] == "33"
finally:
bridge.stop()
+31
View File
@@ -201,6 +201,37 @@ def test_service_routes_pending_answer_to_same_chat(tmp_path):
assert any("AB123" in text for text in drain_outbound(service))
def test_service_survives_answer_failure(tmp_path):
# A resume that raises must come back as a reply, never propagate into the
# front end (the voice adapter calls handle_inbound synchronously).
scheduler = build_scheduler(tmp_path)
service = build_service(scheduler)
scheduler._run_skill(need_input_skill([]), Request("track it", source="simplex:4"))
assert scheduler.pending is not None
def boom(*_args, **_kwargs):
raise RuntimeError("kaboom")
scheduler._answer = boom
service.handle_inbound(InboundMessage(text="AB123", chat_id="4", contact_id="4"))
assert any("kaboom" in text for text in drain_outbound(service))
def test_answer_engine_unavailable_is_fatal(tmp_path):
from semif_agent.engine import EngineUnavailable
scheduler = build_scheduler(tmp_path)
scheduler._run_skill(need_input_skill([]), Request("track it", source="simplex:4"))
def boom(*_args, **_kwargs):
raise EngineUnavailable("engine down")
scheduler._answer = boom
reply = scheduler.answer("AB123")
assert reply.status == "fatal"
assert scheduler.fatal is not None
def test_service_refuses_other_chat_during_pending(tmp_path):
scheduler = build_scheduler(tmp_path)
service = build_service(scheduler)
+1 -1
View File
@@ -39,7 +39,7 @@ DENYLIST = {
"stale llm default": r"qwen2\.5:3b",
"absolute home path": r"/home/abby",
"old venv path": r"semif-venv",
"machine descriptor": r"\b(?:the box|dev box|dev machine|staging box)\b",
"machine descriptor": r"\b(?:dev box|dev machine|staging box)\b",
}
+63 -1
View File
@@ -19,13 +19,15 @@ from semif_agent.simplex_ws import (
parse_chat,
parse_chat_item,
parse_direct_text_item,
parse_read_response,
read_command,
send_text_command,
)
# ---- parsing ----
def direct_item(text="hello", contact_id="4", display="alice", direction="directRcv", kind="text"):
def direct_item(text="hello", contact_id="4", display="alice", direction="directRcv", kind="text", item_id=7):
# v7 wire shape: the Contact's `displayName` is null and the peer name lives
# in `profile.displayName`; `localDisplayName` is auto-suffixed on collision.
# Received text is tagged `rcvMsgContent` with the message under `msgContent`.
@@ -41,6 +43,7 @@ def direct_item(text="hello", contact_id="4", display="alice", direction="direct
},
},
"chatItem": {
"meta": {"itemId": item_id},
"chatDir": {"type": direction},
"content": {
"type": "rcvMsgContent",
@@ -56,6 +59,7 @@ def test_parse_direct_text():
assert message["text"] == "hello"
assert message["contact_id"] == "4"
assert message["display_name"] == "alice"
assert message["item_id"] == "7"
def test_parse_filters_echo_group_and_non_text():
@@ -658,3 +662,61 @@ def test_request_chat_history_without_connection_raises():
daemon = SimplexDaemon("ws://x")
with pytest.raises(RuntimeError):
daemon.request_chat_history("4", timeout=1)
# ---- daemon: read marking ----
def test_read_command_targets_specific_items():
assert read_command("7", ["8", "9"]) == "/_read chat items @7 8,9"
def test_read_command_without_items_reads_the_whole_chat():
assert read_command("@7") == "/_read chat @7"
def test_read_command_ignores_blank_item_ids():
assert read_command("7", [" ", ""]) == "/_read chat @7"
def test_parse_read_response_ok_and_error():
assert parse_read_response({"type": "itemsReadForChat"})["ok"] is True
rejected = parse_read_response(
{"type": "chatCmdError", "chatError": {"type": "error"}}
)
assert rejected["ok"] is False
assert rejected["error"]
assert parse_read_response({})["ok"] is False
def test_mark_read_sends_item_command_and_parses_ok():
daemon = SimplexDaemon("ws://x")
async def scenario():
daemon._loop = asyncio.get_running_loop()
ws = FakeWS(daemon, [{"type": "itemsReadForChat"}])
daemon._ws = ws
return await daemon.mark_read("7", ["11", "12"], timeout=5), ws
result, ws = asyncio.run(scenario())
assert result["ok"] is True
assert [m["cmd"] for m in ws.sent] == ["/_read chat items @7 11,12"]
def test_mark_read_reports_a_rejected_command():
daemon = SimplexDaemon("ws://x")
async def scenario():
daemon._loop = asyncio.get_running_loop()
ws = FakeWS(
daemon, [{"type": "chatCmdError", "chatError": {"type": "error"}}]
)
daemon._ws = ws
return await daemon.mark_read("7", ["11"], timeout=5)
assert asyncio.run(scenario())["ok"] is False
def test_request_mark_read_without_connection_raises():
daemon = SimplexDaemon("ws://x")
with pytest.raises(RuntimeError):
daemon.request_mark_read("7", ["1"], timeout=1)
+96
View File
@@ -612,6 +612,80 @@ def test_canned_response_runs_without_assessment(tmp_path):
assert log.read() == []
def test_assessment_state_carries_skill_action(tmp_path):
"""The assessment decision must see what the skill was meant to do.
Regression: with only `skill: <label>` in the state, the decision model
misfired on a correctly-read result for an ambiguous phrasing, marked a
truthful read failed, and looped the retry ladder until a repair offer. The
skill's declared action now rides in both assessment states.
"""
from semif_agent.skill import SkillRunner
from semif_agent.skills import ActionContext
engine = ScriptedEngine(
choices={"Did the skill achieve": "failure"}, default="success"
)
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
def act(ctx, request):
return ActionResult(action_log="SimpleX message from pepper: hello", new_state="read")
skill = Skill(
name="next_message",
category="simplex",
description="Read the next unread SimpleX message.",
act=act,
)
runner = SkillRunner(ActionContext(engine=engine, config={}), log)
runner.run(skill, Request("What's my next simplex message?"))
outcome_state = engine.calls[0].state
assert "skill action: Read the next unread SimpleX message." in outcome_state
assert "goal: What's my next simplex message?" in outcome_state
requeue_state = engine.calls[1].state
assert "skill action: Read the next unread SimpleX message." in requeue_state
def test_requeue_state_flags_identical_repeat(tmp_path):
"""A retry that would reproduce the identical result is flagged as a no-op
so the requeue decision can choose `complete` instead of looping."""
from semif_agent.skill import SkillRunner
from semif_agent.skills import ActionContext
engine = ScriptedEngine(
choices={"Did the skill achieve": "failure"}, default="success"
)
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
skill = Skill(
name="next_message",
category="simplex",
description="Read the next unread SimpleX message.",
act=lambda ctx, request: ActionResult(
action_log="SimpleX message from pepper: hello", new_state="read"
),
)
runner = SkillRunner(ActionContext(engine=engine, config={}), log)
# First attempt: no prior result, so no no-progress note.
runner.run(skill, Request("What's my next simplex message?"))
assert "identical result" not in engine.calls[1].state
# Same observed result as the previous attempt: flagged as a no-op retry.
engine.calls.clear()
repeat = Request("What's my next simplex message?")
repeat.meta["prev_result"] = "SimpleX message from pepper: hello"
runner.run(skill, repeat)
assert "identical result" in engine.calls[1].state
# A changed result is progress: not flagged.
engine.calls.clear()
progress = Request("What's my next simplex message?")
progress.meta["prev_result"] = "a different previous result"
runner.run(skill, progress)
assert "identical result" not in engine.calls[1].state
def test_navigate_leaf_picks_among_existing_skills_only(tmp_path):
"""Two-stage leaf: create_skill is NOT an option in the leaf softmax. The
@@ -2027,3 +2101,25 @@ def test_exhausted_reentry_offers_repair(tmp_path):
scheduler._finish_run(skill, request, outcome)
assert not any(e["kind"] == "requeued" for e in scheduler.trace.read())
assert any(e["kind"] == "repair_offered" for e in scheduler.trace.read())
def test_requeue_remembers_previous_result(tmp_path):
"""A requeued retry carries the observed result forward so the next
assessment can detect a guaranteed no-op repeat."""
scheduler = _scheduler(tmp_path)
_install_tracking_stub(scheduler)
skill = scheduler.tree["tracking"][0]
request = Request("track my package")
outcome = RunResult(
skill="tracking.check",
success=False,
summary="failed",
action_log="connection refused",
new_state="unchanged",
updated_request="track my package",
)
scheduler._finish_run(skill, request, outcome)
child = scheduler.queue.pop()
assert child is not None
assert child.meta["prev_result"] == "connection refused"
assert any(e["kind"] == "requeued" for e in scheduler.trace.read())
+223 -6
View File
@@ -18,17 +18,22 @@ from semif_agent.voice_transport import VoiceDaemon, VoiceEngines
class FakeAudio:
def __init__(self, frames):
def __init__(self, frames, on_empty=None):
self.frames = list(frames)
#: What `read()` returns when the script runs out: `None` = the input is
#: closed (the loop exits), `b""` = a read timeout (a stalled stream).
self.on_empty = on_empty
self.writes = []
self.closed = False
self.input_opened = False
self.input_opens = 0
def open_input(self, sample_rate, frame_ms, device=""):
self.input_opened = True
self.input_opens += 1
def read(self):
return self.frames.pop(0) if self.frames else None
def read(self, timeout=None):
if self.frames:
return self.frames.pop(0)
return self.on_empty
def open_output(self, sample_rate, device=""):
pass
@@ -132,7 +137,7 @@ def test_wake_word_then_silence_produces_one_utterance():
heard = []
daemon.run(heard.append)
assert heard == ["hello"]
assert engines.audio.input_opened is True
assert engines.audio.input_opens == 1
assert engines.audio.closed is True
# The wake detector is reset after firing.
assert engines.wake.resets >= 1
@@ -170,6 +175,125 @@ def test_min_speech_rejects_short_utterance():
assert engines.stt.calls == []
def test_command_after_pause_is_captured():
# A pause between the wake word and the command (e.g. waiting for the cue
# beep) must not truncate the command: capture waits for speech to begin.
daemon, engines = make_daemon(
[b"WAKE", b"SIL", b"SIL", b"SIL", b"command", b"SIL", b"SIL"]
)
heard = []
daemon.run(heard.append)
assert heard == ["hello"]
assert engines.stt.calls == [b"command" + b"SIL" * 2]
def test_pause_between_wake_and_command_is_tolerated():
# The wake detector can fire inside the wake phrase, so the frames after it
# are the phrase's tail, not the command; a natural pause before the command
# must not end the capture (the bug that made repeated asks fail).
daemon, engines = make_daemon(
[b"WAKE", b"tail", b"SIL", b"SIL", b"SIL", b"SIL", b"SIL", b"SIL",
b"command", b"SIL", b"SIL"]
)
heard = []
daemon.run(heard.append)
assert heard == ["hello"]
assert b"command" in engines.stt.calls[0]
def test_short_command_still_endpoints():
# Once enough speech is in hand the normal silence endpoint applies, so a
# command is not left waiting on the longer initial tolerance.
daemon, engines = make_daemon(
[b"WAKE", b"a", b"b", b"c", b"d", b"e", b"f", b"g", b"h",
b"SIL", b"SIL", b"SIL"],
config={"vad": {"silence_ms": 160, "min_speech_ms": 80,
"min_command_ms": 400, "initial_silence_ms": 2000}},
)
heard = []
daemon.run(heard.append)
assert heard == ["hello"]
# It ended on the 160 ms endpoint (two silent frames), not on the longer
# initial tolerance.
assert engines.stt.calls[0] == b"abcdefgh" + b"SIL" * 2
def test_wake_without_command_times_out(monkeypatch):
# Wake fires but the user never speaks a command: no utterance is produced
# (traced `voice_no_command`) instead of capturing the wake frame as one.
import semif_agent.voice_transport as vt
ticks = iter([0.0, 0.0, 3000.0])
monkeypatch.setattr(vt.time, "time", lambda: next(ticks))
daemon, engines = make_daemon([b"SIL", b"SIL"])
events = []
daemon._event = lambda kind, **kw: events.append(kind)
utterance = daemon._collect(engines, b"WAKE", wait_for_speech_ms=3000)
assert utterance == b""
assert "voice_no_command" in events
# ---- capture-stream watchdog ----------------------------------------------
def test_capture_stall_reopens_input(monkeypatch):
# A stalled PortAudio/ALSA callback never delivers another frame; the loop
# must reopen the input instead of blocking forever.
import semif_agent.voice_transport as vt
daemon, engines = make_daemon([])
engines.audio.on_empty = b"" # every read times out (a stalled stream)
events = []
daemon._event = lambda kind, **kw: events.append(kind)
clock = iter([100.0, 100.5, 106.0])
monkeypatch.setattr(vt.time, "time", lambda: next(clock))
assert daemon._read_frame(engines) == b"" # first timeout: stall starts
assert daemon._read_frame(engines) == b"" # still stalled, below the limit
assert daemon._read_frame(engines) == b"" # past stall_timeout_s -> reopen
assert "voice_stream_stalled" in events
assert "voice_stream_reopened" in events
assert engines.audio.input_opens == 1
assert engines.audio.closed is True # closed before reopening
def test_capture_stall_reopen_failure_is_traced(monkeypatch):
import semif_agent.voice_transport as vt
daemon, engines = make_daemon([])
engines.audio.on_empty = b""
def boom(sample_rate, frame_ms, device=""):
raise RuntimeError("device busy")
engines.audio.open_input = boom
events = []
daemon._event = lambda kind, **kw: events.append(kind)
clock = iter([100.0, 106.0])
monkeypatch.setattr(vt.time, "time", lambda: next(clock))
monkeypatch.setattr(vt.time, "sleep", lambda *_: None)
daemon._read_frame(engines)
daemon._read_frame(engines)
assert "voice_stream_reopen_failed" in events
def test_watchdog_disabled_uses_blocking_read(monkeypatch):
# read_timeout_s=0 restores the old blocking read (no timeout kwarg passed).
daemon, engines = make_daemon(
[], config={"audio": {"frame_ms": 80, "sample_rate": 16000, "read_timeout_s": 0}}
)
seen = {}
def read(timeout=None):
seen["timeout"] = timeout
return None
engines.audio.read = read
assert daemon._read_frame(engines) is None
assert seen["timeout"] is None
# ---- half-duplex / speaking ------------------------------------------------
@@ -232,6 +356,9 @@ def test_adapter_emits_inbound_message():
seen = []
adapter._on_inbound = seen.append
adapter._on_utterance(" hello there ")
# The utterance is queued for the worker, not run on the audio thread.
assert adapter._inbound.qsize() == 1
adapter._handle(adapter._inbound.get())
assert len(seen) == 1
assert seen[0].text == "hello there"
assert seen[0].chat_id == "mic"
@@ -245,6 +372,33 @@ def test_adapter_ignores_empty_utterance():
adapter._on_inbound = seen.append
adapter._on_utterance(" ")
assert seen == []
assert adapter._inbound.empty()
def test_adapter_worker_handles_then_stops():
adapter = VoiceAdapter({})
seen = []
adapter._on_inbound = seen.append
adapter._on_utterance("one")
adapter._inbound.put(None) # sentinel stops the worker
adapter._inbound_worker()
assert [m.text for m in seen] == ["one"]
def test_adapter_contains_handler_error():
# A task that raises must not kill the front end: the worker traces it and
# speaks an apology instead of propagating.
adapter = VoiceAdapter({})
def boom(message):
raise RuntimeError("kaboom")
adapter._on_inbound = boom
spoken = []
adapter.daemon.speak = lambda text: spoken.append(text)
adapter._on_utterance("do the thing")
adapter._handle(adapter._inbound.get()) # must not raise
assert spoken and "wrong" in spoken[0]
def test_adapter_is_result_only():
@@ -313,3 +467,66 @@ def test_resample_pcm16():
assert len(_resample_pcm16(pcm, 44100, 16000)) // 2 == 160
assert _resample_pcm16(pcm, 44100, 44100) == pcm
assert _resample_pcm16(b"", 44100, 16000) == b""
# ---- wake-word model pinning (community model, no network) ------------------
def _load_voice_models():
import importlib.util
from pathlib import Path
path = Path(__file__).resolve().parent.parent / "scripts" / "voice-models.py"
spec = importlib.util.spec_from_file_location("voice_models_script", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_wake_word_pin_resolves_from_model_dir(tmp_path):
import hashlib
from semif_agent.voice_transport import resolve_model_path
module = _load_voice_models()
pins = module.pinned_wake_models()
assert "hey_computer" in pins
ref = pins["hey_computer"]
assert ref["url"].endswith("/hey_computer.onnx")
assert len(ref["sha256"]) == len(hashlib.sha256(b"").hexdigest())
stub = tmp_path / "hey_computer.onnx"
stub.write_bytes(b"stub")
assert resolve_model_path("hey_computer", str(tmp_path), (".onnx", ".tflite")) == str(stub)
def test_download_wake_file_verifies_and_skips_existing(tmp_path):
import hashlib
module = _load_voice_models()
data = b"fake-openwakeword-model"
source = tmp_path / "src.onnx"
source.write_bytes(data)
ref = {"url": source.as_uri(), "sha256": hashlib.sha256(data).hexdigest()}
wake_dir = tmp_path / "wake"
module.download_wake_file("hey_computer", ref, wake_dir)
dest = wake_dir / "hey_computer.onnx"
assert dest.read_bytes() == data
# Idempotent: a present, matching file is not re-fetched.
module.download_wake_file("hey_computer", ref, wake_dir)
assert dest.read_bytes() == data
def test_download_wake_file_rejects_sha_mismatch(tmp_path):
import pytest
module = _load_voice_models()
source = tmp_path / "src.onnx"
source.write_bytes(b"tampered")
ref = {"url": source.as_uri(), "sha256": "0" * 64}
wake_dir = tmp_path / "wake"
with pytest.raises(SystemExit):
module.download_wake_file("hey_computer", ref, wake_dir)
assert not (wake_dir / "hey_computer.onnx").exists()