feat(speech): the speech capability over Cap'n Web, behind a gate

The agent's ears and voice: a server on the home server transcribes
a clip (sox, whisper.cpp) and speaks text (piper), one job at a time.
A gate hands the capability to whoever presents its key; the key comes
from systemd's credentials, not argv.

make test runs the unit tests in Nix's sandbox; make smoke starts a
real server on localhost, speaks a phrase, and hears it back.

Generated-by: Claude Opus 5.5
This commit is contained in:
dckc committed 2026-12-02 15:27:50 -06:00
1 parent 147bfdc55e
commit 65e38c23cf
20 files changed
+468

No files matched your search

+2
View File
@@ -1,3 +1,5 @@
result
__pycache__/
ir-pico/cache/
speech/cache/
node_modules/
+6
View File
@@ -5,3 +5,9 @@ The [README](README.md) says what pdtv26 does and why; this is how to work on it
## Working on it
The tools come from the flake: `nix develop --command make test` in any folder, or `nix develop` once and then `make`. `nix flake check` runs every folder's tests. `make help` in each folder lists what it does, and each module's docstring says what it is. Docs are only for what isn't code, such as [wiring](ir-pico/wiring.md).
## Design
### Capabilities on the wire
The connections are [Cap'n Web](https://github.com/cloudflare/capnweb) over WebSockets, on a private network such as a Tailscale tailnet. A server listens with a [gate](speech/gate.js), not the capability itself: the gate hands the capability to whoever presents its key, compared in constant time, and a client can open and call in one round trip. Keys reach services through systemd's `LoadCredential` (`$CREDENTIALS_DIRECTORY`), never through argv, the environment, or the Nix store.
+6
View File
@@ -21,6 +21,12 @@ Agent: Here's the game. It started ten minutes ago.
The game isn't on 4, 5, or 9. It's on a sports network in the hundreds, behind two **Power** buttons, the **Input** button, and the cable box's remote. Our elders have done their share; let the agent do this.
## Capabilities and confinement
An agent in the living room should be able to do what it's for, and no more. A capability is a reference that both names a service and grants the right to use it. Each part holds capabilities for exactly the services it uses. The brain can press IR buttons and take one camera frame, but it can't reach a shell on the box or anyone's files.
The parts talk over [Cap'n Web](https://github.com/cloudflare/capnweb); [CONTRIBUTING](CONTRIBUTING.md#capabilities-on-the-wire) says how.
## Parts
The agent is built from parts you can buy and solder:
+6
View File
@@ -10,6 +10,11 @@
python = pkgs: pkgs.python3.withPackages (ps: [ ps.pyserial ]);
in
{
packages = forAll (pkgs: {
speech = pkgs.callPackage ./speech/server.nix { };
speech-js = pkgs.callPackage ./speech/default.nix { };
});
# nix develop --command make test
devShells = forAll (pkgs: {
default = pkgs.mkShellNoCC {
@@ -23,6 +28,7 @@
python3 -I -m doctest ir_commands.py pico_tty.py
touch $out
'';
speech = self.packages.${pkgs.system}.speech-js;
});
};
}
+39
View File
@@ -0,0 +1,39 @@
# speech: the agent's ears and voice, as a capability over Cap'n Web.
# Tools come from the flake: nix develop --command make test
WHISPER = https://huggingface.co/ggerganov/whisper.cpp/resolve/main
MODEL = cache/ggml-base.en.bin
VOICES = https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_US/danny/low
VOICE = cache/en_US-danny-low.onnx
PORT = 18024
PHRASE = Put on the ballgame.
UA = pdtv26-speech-setup (curl)
.PHONY: help test smoke
.DELETE_ON_ERROR:
## list targets
help:
@awk -f ../make-help.awk $(MAKEFILE_LIST)
## the unit tests, in Nix's build sandbox: no network, no models
test:
nix build -L --no-link ..#speech-js
## the server and clients, with node, sox, whisper, and piper
cache/speech: $(wildcard *.js *.sh *.nix package*.json) ../flake.nix ../flake.lock
nix build -L --out-link $@ ..#speech
## whisper's English model (about 150 MB; once, kept in cache/)
$(MODEL):
mkdir -p cache
curl -fsSL -A '$(UA)' -o $@ $(WHISPER)/$(notdir $@)
## a piper voice and its config (once, kept in cache/)
cache/en_US-danny-low.%:
mkdir -p cache
curl -fsSL -A '$(UA)' -o $@ $(VOICES)/$(notdir $@)
## a round trip through a real server: speak PHRASE, hear it back, compare
smoke: cache/speech $(MODEL) $(VOICE) $(VOICE).json
./smoke.sh cache/speech/bin $(MODEL) $(VOICE) $(PORT) '$(PHRASE)'
+29
View File
@@ -0,0 +1,29 @@
# pdtv26-speech: the speech capability's JavaScript, and its clients.
# npm runs here, in Nix's build sandbox, from package-lock.json; so do the tests.
# The output is plain JavaScript, the same on every architecture (allowedReferences keeps it so):
# each user supplies its own node, at lib/node_modules/pdtv26-speech/*.js.
{ lib, buildNpmPackage }:
buildNpmPackage {
pname = "pdtv26-speech";
version = "0.1.0";
src = lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.unions [
./package.json ./package-lock.json ./run.js
./gate.js ./gate.test.js ./speech.js ./speech.test.js
./server.js ./hear-client.js ./speak-client.js
];
};
npmDepsHash = "sha256-C7Em37Mm3+mUHqQ2n37JshgLCByzMOlhgoQEex3CnlU=";
dontNpmBuild = true;
npmInstallFlags = [ "--ignore-scripts" ];
doCheck = true;
checkPhase = ''
runHook preCheck
# Every file parses, the server and clients included: no test imports them.
for f in *.js; do node --check "$f"; done
node --test
runHook postCheck
'';
allowedReferences = [ ];
}
+27
View File
@@ -0,0 +1,27 @@
/**
* @file The gate: hands a capability to whoever presents its key.
* A server listens with a gate, not the capability itself, so a connection gets nothing
* until it shows the key: open(key) returns the capability, and pipelines, so a client
* can open and call in one round trip.
*/
import { RpcTarget } from 'capnweb';
import { createHash, timingSafeEqual } from 'node:crypto';
const digest = (s) => createHash('sha256').update(String(s)).digest();
/**
* @param {string} key unguessable, from a credential file
* @param {object} cap what open(key) hands out
*/
export const makeGate = (key, cap) => {
const want = digest(key);
class Gate extends RpcTarget {
/** @param {string} k */
open(k) {
// Digests are the same length whatever k is, so the comparison takes the same time.
if (!timingSafeEqual(digest(k), want)) throw new Error('no such key');
return cap;
}
}
return new Gate();
};
+13
View File
@@ -0,0 +1,13 @@
// Tests for the gate, in process: no network.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { makeGate } from './gate.js';
test('the right key opens the gate; a wrong one is refused', () => {
const cap = { it: 'the capability' };
const gate = makeGate('k3y', cap);
assert.equal(gate.open('k3y'), cap);
assert.throws(() => gate.open('guess'), /no such key/);
assert.throws(() => gate.open(''), /no such key/);
assert.throws(() => gate.open(undefined), /no such key/);
});
+25
View File
@@ -0,0 +1,25 @@
/**
* @file hear-client: send one clip to the speech capability and print the transcript.
* usage: node hear-client.js URL < clip.wav
* The key is in $CREDENTIALS_DIRECTORY/speech-key (systemd LoadCredential), not argv, where ps would show it.
*/
import { newWebSocketRpcSession } from 'capnweb';
import { readFile } from 'node:fs/promises';
import { buffer } from 'node:stream/consumers';
const main = async ([url], env, stdin, stdout) => {
const key = (await readFile(`${env.CREDENTIALS_DIRECTORY}/speech-key`, 'utf8')).trim();
const clip = new Uint8Array(await buffer(stdin));
const gate = newWebSocketRpcSession(url);
try {
// Pipelined: open and transcribe in one round trip.
stdout.write(`${await gate.open(key).transcribe(clip)}\n`);
} finally {
gate[Symbol.dispose]();
}
};
main(process.argv.slice(2), process.env, process.stdin, process.stdout).catch((err) => {
console.error(`hear-client: ${err.message ?? err}`);
process.exit(1);
});
Executable
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# hear.sh MODEL: a WAV clip on stdin, whisper's transcript on stdout.
# The Nix build fills in @sox@ and @whisper@ (server.nix).
set -eu
model=$1
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
cat > "$tmp/in.wav"
# mono, 16-bit, normalized: the box's mics are quiet (speech peaks near -27 dBFS)
@sox@/bin/sox "$tmp/in.wav" -r 16000 -c 1 -b 16 "$tmp/clip.wav" remix - gain -n -3
@whisper@/bin/whisper-cli -m "$model" -f "$tmp/clip.wav" -t 4 -nt -np 2>"$tmp/err" \
|| { cat "$tmp/err" >&2; exit 1; }
+44
View File
@@ -0,0 +1,44 @@
{
"name": "pdtv26-speech",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "pdtv26-speech",
"version": "0.1.0",
"license": "Apache-2.0",
"dependencies": {
"capnweb": "0.13.1",
"ws": "8.23.1"
}
},
"node_modules/capnweb": {
"version": "0.13.1",
"resolved": "https://registry.npmjs.org/capnweb/-/capnweb-0.13.1.tgz",
"integrity": "sha512-JEE/MYKv41blYv5MGGzKiT3DT4qz00AQ+NsmPSdVFVSKuy2/ggUI4aDGJO+jEvAXNXuZURoxo7hCfx+VKbM32g==",
"license": "MIT"
},
"node_modules/ws": {
"version": "8.23.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.23.1.tgz",
"integrity": "sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "pdtv26-speech",
"version": "0.1.0",
"description": "Speech for the agent at the TV: hear (transcribe) and speak, as a capability over Cap'n Web",
"private": true,
"type": "module",
"license": "Apache-2.0",
"scripts": {
"test": "node --test"
},
"dependencies": {
"capnweb": "0.13.1",
"ws": "8.23.1"
}
}
+30
View File
@@ -0,0 +1,30 @@
/**
* @file Helpers for the servers: run a script, and time and log a job.
*/
import { spawn } from 'node:child_process';
/** Run cmd with input on stdin; resolve to its stdout bytes, or reject with its stderr. */
export const runWith = (cmd, args, input) => new Promise((resolve, reject) => {
const child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'] });
const out = [], err = [];
child.stdout.on('data', (d) => out.push(d));
child.stderr.on('data', (d) => err.push(d));
child.on('error', reject);
child.on('close', (code) => code === 0
? resolve(Buffer.concat(out))
: reject(new Error(`${cmd} exit ${code}: ${Buffer.concat(err).toString().trim().slice(-500)}`)));
child.stdin.end(input);
});
/** Time a job and log how it went; failures are logged and rethrown. */
export const timed = async (what, job, describe) => {
const t0 = Date.now();
try {
const result = await job();
console.log(`${what} in ${Date.now() - t0} ms: ${describe(result)}`);
return result;
} catch (err) {
console.error(`${what} failed after ${Date.now() - t0} ms: ${err.message}`);
throw err;
}
};
+36
View File
@@ -0,0 +1,36 @@
/**
* @file speech-server: the speech capability over Cap'n Web, behind a gate.
* usage: node server.js HOST PORT HEAR_SH MODEL SPEAK_SH VOICE
* The key is in $CREDENTIALS_DIRECTORY/speech-key (systemd LoadCredential), not argv, where ps would show it.
* HEAR_SH MODEL reads a WAV on stdin and prints whisper's transcript (hear.sh).
* SPEAK_SH VOICE reads text on stdin and writes piper's WAV of it (speak.sh).
*/
import { WebSocketServer } from 'ws';
import { newWebSocketRpcSession } from 'capnweb';
import { readFile } from 'node:fs/promises';
import { makeGate } from './gate.js';
import { makeSpeech, MAX_CLIP_BYTES } from './speech.js';
import { runWith, timed } from './run.js';
const main = async ([host, port, hearSh, model, speakSh, voice], env) => {
const key = (await readFile(`${env.CREDENTIALS_DIRECTORY}/speech-key`, 'utf8')).trim();
const speech = makeSpeech(
(clip) => timed(`heard ${clip.length} bytes`,
async () => (await runWith(hearSh, [model], clip)).toString().trim(), (text) => text),
(text) => timed(`spoke ${text.length} chars`,
async () => new Uint8Array(await runWith(speakSh, [voice], text)), (wav) => `${wav.length} bytes of WAV`),
);
const gate = makeGate(key, speech);
// A clip travels as base64 inside JSON: 4/3 of its size, plus a little.
const wss = new WebSocketServer({ host, port: Number(port), maxPayload: Math.ceil(MAX_CLIP_BYTES * 1.4) });
wss.on('connection', (ws, req) => {
console.log(`connection from ${req.socket.remoteAddress}`);
newWebSocketRpcSession(ws, gate);
});
console.log(`speech-server: listening on ${host}:${port}`);
};
main(process.argv.slice(2), process.env).catch((err) => {
console.error(err);
process.exit(1);
});
+23
View File
@@ -0,0 +1,23 @@
# The speech server and clients, with node, and the sox, whisper, and piper the server's scripts use.
# bin/speech-server HOST PORT MODEL VOICE
# bin/hear-client URL < clip.wav
# bin/speak-client URL < text > speech.wav
{ callPackage, runCommand, nodejs-slim, sox, whisper-cpp, piper-tts }:
let
js = callPackage ./default.nix { };
dir = "${js}/lib/node_modules/pdtv26-speech";
in
runCommand "pdtv26-speech" { } ''
mkdir -p $out/bin
substitute ${./hear.sh} $out/bin/hear.sh --subst-var-by sox ${sox} --subst-var-by whisper ${whisper-cpp}
substitute ${./speak.sh} $out/bin/speak.sh --subst-var-by piper ${piper-tts}
chmod +x $out/bin/hear.sh $out/bin/speak.sh
cat > $out/bin/speech-server <<EOF
#!/bin/sh
exec ${nodejs-slim}/bin/node ${dir}/server.js "\$1" "\$2" $out/bin/hear.sh "\$3" $out/bin/speak.sh "\$4"
EOF
for c in hear-client speak-client; do
printf '#!/bin/sh\nexec %s %s/%s.js "$@"\n' ${nodejs-slim}/bin/node ${dir} $c > $out/bin/$c
done
chmod +x $out/bin/speech-server $out/bin/hear-client $out/bin/speak-client
''
+33
View File
@@ -0,0 +1,33 @@
#!/bin/sh
# smoke.sh BIN MODEL VOICE PORT PHRASE: a speech round trip, by way of a real server and clients.
# Starts BIN/speech-server on localhost with a throwaway key, has it speak PHRASE,
# then hear the WAV back, and compares the words, ignoring case and punctuation.
set -eu
bin=$1 model=$2 voice=$3 port=$4 phrase=$5
tmp=$(mktemp -d)
pid=
trap '[ -n "$pid" ] && kill "$pid" 2>/dev/null; rm -rf "$tmp"' EXIT
umask 077
head -c 20 /dev/urandom | base32 > "$tmp/speech-key"
export CREDENTIALS_DIRECTORY="$tmp"
"$bin/speech-server" 127.0.0.1 "$port" "$model" "$voice" > "$tmp/server.log" 2>&1 &
pid=$!
tries=0
until grep -q listening "$tmp/server.log"; do
tries=$((tries + 1))
[ "$tries" -le 50 ] || { cat "$tmp/server.log" >&2; exit 1; }
sleep 0.2
done
url=ws://127.0.0.1:$port/
printf '%s\n' "$phrase" | "$bin/speak-client" "$url" > "$tmp/said.wav"
heard=$("$bin/hear-client" "$url" < "$tmp/said.wav")
cat "$tmp/server.log"
words() { printf '%s' "$1" | tr -cd 'A-Za-z' | tr A-Z a-z; }
echo "said: $phrase"
echo "heard: $heard"
[ "$(words "$phrase")" = "$(words "$heard")" ] || { echo "smoke: they differ" >&2; exit 1; }
echo "smoke: same words"
+24
View File
@@ -0,0 +1,24 @@
/**
* @file speak-client: have the speech capability speak text; write the WAV to stdout.
* usage: node speak-client.js URL < text > speech.wav
* The key is in $CREDENTIALS_DIRECTORY/speech-key (systemd LoadCredential), not argv.
*/
import { newWebSocketRpcSession } from 'capnweb';
import { readFile } from 'node:fs/promises';
import { text } from 'node:stream/consumers';
const main = async ([url], env, stdin, stdout) => {
const key = (await readFile(`${env.CREDENTIALS_DIRECTORY}/speech-key`, 'utf8')).trim();
const words = (await text(stdin)).trim();
const gate = newWebSocketRpcSession(url);
try {
stdout.write(await gate.open(key).speak(words));
} finally {
gate[Symbol.dispose]();
}
};
main(process.argv.slice(2), process.env, process.stdin, process.stdout).catch((err) => {
console.error(`speak-client: ${err.message ?? err}`);
process.exit(1);
});
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# speak.sh VOICE: text on stdin, piper's WAV of it on stdout. VOICE is an .onnx with its .onnx.json beside it.
# The Nix build fills in @piper@ (server.nix).
set -eu
voice=$1
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
@piper@/bin/piper -m "$voice" -f "$tmp/out.wav" 2>"$tmp/err" || { cat "$tmp/err" >&2; exit 1; }
cat "$tmp/out.wav"
+44
View File
@@ -0,0 +1,44 @@
/**
* @file The speech capability: the agent's ears and voice.
* Who can transcribe a clip, or have text spoken, is who holds a Speech.
* @see gate.js, which hands one out; server.js, which serves it
*/
import { RpcTarget } from 'capnweb';
/** About 30 s of 32-bit stereo at 16 kHz, the box's mics' own format. */
export const MAX_CLIP_BYTES = 4_000_000;
/** A spoken reply: a few sentences. */
export const MAX_SPEAK_CHARS = 1000;
/**
* Speech: transcribe(clip) returns the text; speak(text) returns a WAV of it.
* One job at a time: whisper and piper each use all of a small server's cores.
* @param {(clip: Uint8Array) => Promise<string>} transcribe
* @param {(text: string) => Promise<Uint8Array>} [speak]
*/
export const makeSpeech = (transcribe, speak) => {
let last = Promise.resolve();
const inTurn = (job) => {
const result = last.then(job);
last = result.catch(() => {});
return result;
};
class Speech extends RpcTarget {
/** @param {Uint8Array} clip a WAV file */
transcribe(clip) {
if (!(clip instanceof Uint8Array)) throw new TypeError('clip must be bytes');
if (clip.length > MAX_CLIP_BYTES) throw new RangeError(`clip over ${MAX_CLIP_BYTES} bytes`);
return inTurn(() => transcribe(clip));
}
/** @param {string} text */
speak(text) {
if (!speak) throw new Error('no voice here');
if (typeof text !== 'string' || !text.trim()) throw new TypeError('speak needs text');
if (text.length > MAX_SPEAK_CHARS) throw new RangeError(`text over ${MAX_SPEAK_CHARS} chars`);
return inTurn(() => speak(text));
}
}
return new Speech();
};
+45
View File
@@ -0,0 +1,45 @@
// Tests for the speech capability, in process: no network, no whisper, no piper.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { makeSpeech, MAX_CLIP_BYTES, MAX_SPEAK_CHARS } from './speech.js';
const clip = new Uint8Array([82, 73, 70, 70]); // "RIFF"
test('transcribe takes bytes, and not too many', async () => {
const speech = makeSpeech(async (c) => `${c.length} bytes`);
assert.equal(await speech.transcribe(clip), '4 bytes');
assert.throws(() => speech.transcribe('UklGRg=='), /must be bytes/);
assert.throws(() => speech.transcribe(new Uint8Array(MAX_CLIP_BYTES + 1)), /over/);
});
test('one clip at a time, and a failure does not stall the next', async () => {
const log = [];
let n = 0;
const speech = makeSpeech(async () => {
const i = ++n;
log.push(`start ${i}`);
await new Promise((r) => setTimeout(r, 10));
log.push(`end ${i}`);
if (i === 1) throw new Error('whisper failed');
return `text ${i}`;
});
const [a, b] = await Promise.allSettled([speech.transcribe(clip), speech.transcribe(clip)]);
assert.equal(a.status, 'rejected');
assert.equal(b.value, 'text 2');
assert.deepEqual(log, ['start 1', 'end 1', 'start 2', 'end 2']);
});
test('speak takes text, not too much, and shares the one-at-a-time turn', async () => {
const log = [];
const speech = makeSpeech(
async () => { log.push('transcribe'); return 'hi'; },
async (text) => { log.push(`speak ${text}`); return new Uint8Array([82, 73, 70, 70]); },
);
const [heard, wav] = await Promise.all([speech.transcribe(clip), speech.speak('Hello.')]);
assert.equal(heard, 'hi');
assert.deepEqual([...wav], [82, 73, 70, 70]);
assert.deepEqual(log, ['transcribe', 'speak Hello.']);
assert.throws(() => speech.speak(''), /needs text/);
assert.throws(() => speech.speak('x'.repeat(MAX_SPEAK_CHARS + 1)), /over/);
assert.throws(() => makeSpeech(async () => '').speak('hi'), /no voice/);
});