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

+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);
});