Files
dckc 2e7156dc36
check / check (push) Canceled after 0s
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
2026-12-02 15:52:55 -06:00

61 lines
1.8 KiB
JavaScript

/**
* @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;
/**
* 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.
*/
export class Speech extends RpcTarget {
#transcribe;
#speak;
/** @type {Promise<unknown>} the job before this one */
#last = Promise.resolve();
/**
* @param {(clip: Uint8Array) => Promise<string>} transcribe
* @param {(text: string) => Promise<Uint8Array>} [speak]
*/
constructor(transcribe, speak) {
super();
this.#transcribe = transcribe;
this.#speak = speak;
}
/**
* @template T
* @param {() => Promise<T>} job
* @returns {Promise<T>}
*/
#inTurn(job) {
const result = this.#last.then(job);
this.#last = result.catch(() => {});
return result;
}
/** @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 this.#inTurn(() => this.#transcribe(clip));
}
/** @param {string} text */
speak(text) {
const speak = this.#speak;
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 this.#inTurn(() => speak(text));
}
}