Opening menu and hands-free mode: call an agent by name (0.3.0)

The app now opens on a menu, which is the root page: "Hands free" first,
"Agents" second. Agents is the 0.2.0 app unchanged. Hands free is the same
agents, conversations and question path with one flag set: the microphone
listens while the app is at rest and the app does not leave by itself.
The mode is never remembered; every launch starts at the menu with the
microphone closed, and double tap at Ready returns to the menu and closes
it.

Client: a loudness-only speech segmenter (core/vad.ts) cuts the stream
into utterances; each goes to the bridge for a wake check. "Wendy, <q>"
becomes a text turn to Wendy, with what was heard shown while she works.
A name alone starts a recording that sends itself when the speaker stops.
The status line starts with a dot for exactly as long as the microphone is
open at rest. In wake mode every microphone open and close goes through
one serialised reconciler; without the option the old path is untouched.

Bridge: POST /v1/wake transcribes one utterance in memory and reports
whether it BEGAN with an agent's name (first word of the display name, or
an alias from HERMEVEN_AGENT_<ID>_WAKE). Exact match only; a near miss is
reported as one word and never acted on. Creates no turn, stores nothing,
returns and logs nothing that was not addressed to an agent. One check at
a time per device, HERMEVEN_WAKE_CHECKS_PER_MINUTE (30).

Docs: decision 0004, bridge API, security gaps 3c/3d, device plan D.
The manifest's microphone description changed.

Not reviewed, not deployed, not uploaded, not device-tested.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Dan
2026-11-28 10:52:06 -08:00
co-authored by Claude Fable 5.2
parent 75b7ea1eff
commit e1d183b54d
26 changed files with 1847 additions and 48 deletions
+42 -7
View File
@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { AUDIO_FORMAT, DEFAULT_LIMITS } from '@hermeven/contracts';
import { validateManifest, type ModelManifest } from './stt/modelStore.mjs';
import { wakeWordsFor } from './wake.ts';
export interface AgentConfig {
/** `default` for the main agent; otherwise the id from HERMEVEN_AGENTS. */
@@ -10,6 +11,11 @@ export interface AgentConfig {
name: string;
baseUrl: string;
apiKey: string;
/**
* What this agent answers to when spoken first ("Wendy, ..."): the first word of its name plus
* any aliases, lower-case. Empty = it cannot be called by voice. Never sent to a client.
*/
wakeWords: string[];
}
export const DEFAULT_AGENT_ID = 'default';
@@ -65,6 +71,8 @@ export interface BridgeConfig {
textMaxChars: number;
audioMaxBytes: number;
turnsPerMinute: number;
/** Wake checks (speech heard while the app is open, tested for a leading agent name). */
wakeChecksPerMinute: number;
pairingAttemptsPerMinute: number;
};
credentials: {
@@ -165,10 +173,32 @@ function agentName(key: string, raw: string | undefined, fallback: string): stri
* profile its own key and refuses the default's, so every extra agent needs
* HERMEVEN_AGENT_<ID>_API_KEY. Optional: HERMEVEN_AGENT_<ID>_PROFILE (default: the id) and
* HERMEVEN_AGENT_<ID>_NAME (default: the id, capitalised).
*
* An agent is called by voice with the first word of its name. HERMEVEN_AGENT_<ID>_WAKE (for the
* default agent, HERMEVEN_AGENT_WAKE) adds comma-separated aliases, for spellings the speech
* model produces instead ("kody"). Two agents may not answer to the same word.
*/
function wakeWords(key: string, raw: string | undefined, name: string): string[] {
const aliases = (raw ?? '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
if (aliases.length > 8 || aliases.some((a) => a.length > 32)) throw new ConfigError(`${key} takes at most 8 aliases of at most 32 characters`);
return wakeWordsFor(name, aliases);
}
function agentsFromEnv(env: NodeJS.ProcessEnv, baseUrl: string, defaultKey: string): AgentConfig[] {
const defaultName = agentName('HERMEVEN_AGENT_NAME', env.HERMEVEN_AGENT_NAME, 'Agent');
const agents: AgentConfig[] = [
{ id: DEFAULT_AGENT_ID, name: agentName('HERMEVEN_AGENT_NAME', env.HERMEVEN_AGENT_NAME, 'Agent'), baseUrl, apiKey: defaultKey },
{
id: DEFAULT_AGENT_ID,
name: defaultName,
baseUrl,
apiKey: defaultKey,
// The placeholder name "Agent" is not something to listen for: the default agent answers
// to a name only once the owner has given it one (or an alias).
wakeWords: wakeWords('HERMEVEN_AGENT_WAKE', env.HERMEVEN_AGENT_WAKE, env.HERMEVEN_AGENT_NAME ? defaultName : ''),
},
];
const ids = (env.HERMEVEN_AGENTS ?? '')
.split(',')
@@ -182,12 +212,16 @@ function agentsFromEnv(env: NodeJS.ProcessEnv, baseUrl: string, defaultKey: stri
if (!apiKey) throw new ConfigError(`${prefix}_API_KEY is required: Hermes gives each profile its own API key`);
const profile = env[`${prefix}_PROFILE`] || id;
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(profile)) throw new ConfigError(`${prefix}_PROFILE is not a valid profile name`);
agents.push({
id,
name: agentName(`${prefix}_NAME`, env[`${prefix}_NAME`], id.charAt(0).toUpperCase() + id.slice(1)),
baseUrl: `${baseUrl}/p/${profile}`,
apiKey,
});
const name = agentName(`${prefix}_NAME`, env[`${prefix}_NAME`], id.charAt(0).toUpperCase() + id.slice(1));
agents.push({ id, name, baseUrl: `${baseUrl}/p/${profile}`, apiKey, wakeWords: wakeWords(`${prefix}_WAKE`, env[`${prefix}_WAKE`], name) });
}
const claimed = new Map<string, string>();
for (const agent of agents) {
for (const word of agent.wakeWords) {
const other = claimed.get(word);
if (other) throw new ConfigError(`Agents "${other}" and "${agent.id}" would both answer to "${word}". Give one a different name or alias.`);
claimed.set(word, agent.id);
}
}
if (agents.length > 16) throw new ConfigError('HERMEVEN_AGENTS lists too many agents (at most 15 besides the default)');
return agents;
@@ -292,6 +326,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
// One extra second of headroom over the capture cap for frame alignment.
audioMaxBytes: (captureMaxSeconds + 1) * AUDIO_FORMAT.bytesPerSecond,
turnsPerMinute: int(env, 'HERMEVEN_TURNS_PER_MINUTE', 20, 1, 600),
wakeChecksPerMinute: int(env, 'HERMEVEN_WAKE_CHECKS_PER_MINUTE', 30, 1, 600),
pairingAttemptsPerMinute: int(env, 'HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE', 5, 1, 60),
},
credentials: {
+48
View File
@@ -11,12 +11,14 @@ import {
PairingClaimRequest,
SCHEMA_VERSION,
TextTurnRequest,
WakeQuery,
type ConversationResponse,
type DeviceCredential,
type DeviceStatusResponse,
type ErrorCode,
type ErrorResponse,
type Limits,
type WakeResponse,
} from '@hermeven/contracts';
import { DEFAULT_AGENT_ID, type BridgeConfig } from './config.ts';
import type { DeviceRow, Devices } from './devices.ts';
@@ -24,6 +26,7 @@ import type { HermesAdapter } from './hermes/adapter.ts';
import { RateLimiter } from './ratelimit.ts';
import type { SttAdapter } from './stt/adapter.ts';
import type { TurnEngine } from './turns.ts';
import { matchWake } from './wake.ts';
export interface ServerDeps {
config: BridgeConfig;
@@ -142,6 +145,9 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
const pairingLimiter = new RateLimiter(config.limits.pairingAttemptsPerMinute, 60_000);
const turnLimiter = new RateLimiter(config.limits.turnsPerMinute, 60_000);
const readLimiter = new RateLimiter(600, 60_000);
const wakeLimiter = new RateLimiter(config.limits.wakeChecksPerMinute, 60_000);
/** Devices with a wake check being transcribed: one at a time each. */
const wakeBusy = new Set<string>();
function authenticate(req: FastifyRequest): DeviceRow {
const header = req.headers.authorization ?? '';
@@ -305,6 +311,48 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
return engine.toResult(result.turn, result.replayed);
});
// -------------------------------------------------------------------- wake
/**
* One stretch of speech heard while the app was open: does it begin with an agent's name?
* Transcribed in memory and dropped. No turn, no row, nothing sent to any agent; a match only
* tells the app who was addressed and what was said after the name, and the app then asks in
* the ordinary way. Speech that was not for an agent is not returned and never logged.
*/
app.post('/v1/wake', async (req): Promise<WakeResponse> => {
const device = authenticate(req);
const contentType = String(req.headers['content-type'] ?? '').split(';')[0]!.trim().toLowerCase();
if (contentType !== 'application/octet-stream') throw new ApiError('unsupported_media', 'Unsupported content type.');
const query = req.query as Record<string, unknown>;
requireVersion(query.schema_version);
if (!check(WakeQuery, query)) throw new ApiError('invalid_request', 'Malformed wake request.');
const pcm = req.body as Buffer;
if (!Buffer.isBuffer(pcm) || pcm.length === 0) throw new ApiError('invalid_request', 'Audio body is empty.');
if (pcm.length % 2 !== 0) throw new ApiError('invalid_request', 'Audio is not whole 16-bit samples.');
// Nobody can be called by voice (no speech-to-text, or no agent with a usable name): the
// app is told so once and stops sending audio.
if (!deps.stt.configured || !config.agents.some((a) => a.wakeWords.length > 0)) throw new ApiError('not_found', 'Not found.');
if (wakeBusy.has(device.id) || !wakeLimiter.take(device.id)) throw new ApiError('rate_limited', 'Too many requests. Wait a moment.');
const none: WakeResponse = { schema_version: SCHEMA_VERSION, matched: false, agent_id: null, text: '', near_miss: null };
wakeBusy.add(device.id);
const abort = new AbortController();
const timer = setTimeout(() => abort.abort(), config.limits.transcribeDeadlineSeconds * 1000);
try {
const transcript = await deps.stt.transcribe({ pcm, locale: query.locale, signal: abort.signal });
const match = matchWake(transcript, config.agents);
if (!match.matched) return { ...none, near_miss: match.nearMiss };
req.log.info({ device_id: device.id, agent_id: match.agentId, name_only: match.text === '' }, 'wake.matched');
return { ...none, matched: true, agent_id: match.agentId, text: match.text.slice(0, config.limits.textMaxChars) };
} catch (err) {
// A failed transcription is "nothing was addressed to anyone": there is no request to fail.
req.log.warn({ device_id: device.id, err_name: err instanceof Error ? err.name : 'unknown' }, 'wake.transcription_failed');
return none;
} finally {
clearTimeout(timer);
wakeBusy.delete(device.id);
}
});
app.get('/v1/turns/:requestId', async (req) => {
const device = authenticate(req);
const { requestId } = req.params as { requestId: string };
+90
View File
@@ -0,0 +1,90 @@
/**
* Wake names: deciding whether something that was said is addressed to an agent.
*
* The glasses app listens all the time it is open and sends each stretch of speech here. Most
* of it is not for an agent at all, so the rule is deliberately strict: the agent's name must
* be the FIRST thing said (an optional "hey"/"ok" aside). A name in the middle of a sentence
* never counts. A match is exact, against the name or an alias the owner configured; a
* near-miss is reported as such and never acted on, because an agent can do things and a
* misheard word must not start it.
*/
export interface WakeAgent {
id: string;
/** Lower-case words or short phrases, each already normalised with `wakeTokens`. */
wakeWords: string[];
}
export type WakeMatch =
| { matched: true; agentId: string; text: string }
| { matched: false; nearMiss: string | null };
const GREETINGS = new Set(['hey', 'hi', 'ok', 'okay', 'yo', 'hello']);
const WORD = /[\p{L}\p{N}]+(?:['’][\p{L}]+)*/gu;
/** The words of a phrase, lower-case, without punctuation. */
export function wakeTokens(phrase: string): string[] {
return (phrase.normalize('NFC').toLowerCase().match(WORD) ?? []).map((w) => w.replace(/’/g, "'"));
}
/**
* The wake words an agent answers to: the first word of its display name, plus any aliases.
* A first word that is not at least three letters is not usable as a wake word.
*/
export function wakeWordsFor(name: string, aliases: string[]): string[] {
const out: string[] = [];
const first = wakeTokens(name)[0];
if (first && /^\p{L}{3,}$/u.test(first)) out.push(first);
for (const alias of aliases) {
const phrase = wakeTokens(alias).join(' ');
if (phrase && !out.includes(phrase)) out.push(phrase);
}
return out;
}
function distance(a: string, b: string): number {
let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
for (let i = 1; i <= a.length; i++) {
const row = [i];
for (let j = 1; j <= b.length; j++) {
row[j] = Math.min(prev[j]! + 1, row[j - 1]! + 1, prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1));
}
prev = row;
}
return prev[b.length]!;
}
export function matchWake(transcript: string, agents: WakeAgent[]): WakeMatch {
const text = transcript.normalize('NFC');
const words = [...text.matchAll(WORD)].map((m) => ({ word: m[0].toLowerCase().replace(/’/g, "'"), end: m.index + m[0].length }));
// Anything before the first word other than space and punctuation (a bracketed sound
// description, say) is still "before the first word": only words are compared.
let start = 0;
if (words.length > 1 && GREETINGS.has(words[0]!.word)) start = 1;
if (words.length <= start) return { matched: false, nearMiss: null };
// Longest phrase first, so an alias of two words wins over a one-word name that begins it.
const candidates = agents
.flatMap((agent) => agent.wakeWords.map((phrase) => ({ agentId: agent.id, tokens: phrase.split(' ') })))
.sort((a, b) => b.tokens.length - a.tokens.length);
for (const candidate of candidates) {
const { tokens } = candidate;
if (words.length - start < tokens.length) continue;
if (!tokens.every((token, i) => words[start + i]!.word === token)) continue;
const rest = text
.slice(words[start + tokens.length - 1]!.end)
.replace(/^[\s,.:;!?…\-–—"'’”]+/u, '')
.trim();
return { matched: true, agentId: candidate.agentId, text: rest ? rest.charAt(0).toUpperCase() + rest.slice(1) : '' };
}
const first = words[start]!.word;
for (const candidate of candidates) {
if (candidate.tokens.length !== 1) continue;
const name = candidate.tokens[0]!;
const allowed = name.length >= 6 ? 2 : name.length >= 4 ? 1 : 0;
if (allowed > 0 && Math.abs(first.length - name.length) <= allowed && distance(first, name) <= allowed) {
return { matched: false, nearMiss: first.slice(0, 24) };
}
}
return { matched: false, nearMiss: null };
}
+70
View File
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest';
import { ConfigError, loadConfig } from '../src/config.ts';
import { matchWake, wakeWordsFor } from '../src/wake.ts';
const agents = [
{ id: 'default', wakeWords: ['pepper'] },
{ id: 'wendy', wakeWords: ['wendy'] },
{ id: 'cody', wakeWords: ['cody', 'kody', 'code e'] },
];
describe('wake names', () => {
it('a name said first addresses that agent, and what follows is the question', () => {
expect(matchWake(' Wendy, what is on my calendar?', agents)).toEqual({ matched: true, agentId: 'wendy', text: 'What is on my calendar?' });
expect(matchWake('Pepper. Send Dan a message.', agents)).toEqual({ matched: true, agentId: 'default', text: 'Send Dan a message.' });
expect(matchWake('cody are the tests passing', agents)).toEqual({ matched: true, agentId: 'cody', text: 'Are the tests passing' });
});
it('a greeting before the name is allowed, and nothing else is', () => {
expect(matchWake('Hey Wendy, hello', agents)).toMatchObject({ matched: true, agentId: 'wendy', text: 'Hello' });
expect(matchWake('OK, Pepper: lights off', agents)).toMatchObject({ matched: true, agentId: 'default', text: 'Lights off' });
expect(matchWake('So Wendy, hello', agents).matched).toBe(false);
expect(matchWake('Hey', agents).matched).toBe(false);
});
it('the name alone matches with an empty question', () => {
expect(matchWake('Wendy.', agents)).toEqual({ matched: true, agentId: 'wendy', text: '' });
expect(matchWake('Hey Cody!', agents)).toEqual({ matched: true, agentId: 'cody', text: '' });
});
it('a name anywhere but first never matches', () => {
for (const said of ['I told Wendy about it', 'ask Pepper later', 'is that Cody', '', ' ', '[BLANK_AUDIO]', '(wind blowing)']) {
expect(matchWake(said, agents).matched, said).toBe(false);
}
});
it('aliases match, including one of two words, and the longest wins', () => {
expect(matchWake('Kody, status', agents)).toMatchObject({ matched: true, agentId: 'cody', text: 'Status' });
expect(matchWake('Code E, status', agents)).toMatchObject({ matched: true, agentId: 'cody', text: 'Status' });
});
it('a word that is only close to a name is reported as a near miss and does not match', () => {
expect(matchWake('Wendi, what time is it', agents)).toEqual({ matched: false, nearMiss: 'wendi' });
expect(matchWake('Copy that', agents)).toEqual({ matched: false, nearMiss: 'copy' });
expect(matchWake('Paper is on the desk', agents)).toEqual({ matched: false, nearMiss: 'paper' });
expect(matchWake('Wednesday works', agents)).toEqual({ matched: false, nearMiss: null });
});
it('wake words come from the first word of the name plus aliases', () => {
expect(wakeWordsFor('Cody R.', ['Kody', ' code-e '])).toEqual(['cody', 'kody', 'code e']);
expect(wakeWordsFor('R2', [])).toEqual([]);
expect(wakeWordsFor('', ['Friday'])).toEqual(['friday']);
});
});
describe('wake names in configuration', () => {
const base = { HERMES_API_KEY: 'k'.repeat(24), STT_PROVIDER: 'none' };
it('each agent answers to its name; the unnamed default agent answers to nothing', () => {
const config = loadConfig({ ...base, HERMEVEN_AGENTS: 'wendy', HERMEVEN_AGENT_WENDY_API_KEY: 'w'.repeat(24), HERMEVEN_AGENT_WENDY_WAKE: 'wendi, windy' });
expect(config.agents.map((a) => a.wakeWords)).toEqual([[], ['wendy', 'wendi', 'windy']]);
expect(loadConfig({ ...base, HERMEVEN_AGENT_NAME: 'Pepper' }).agents[0]!.wakeWords).toEqual(['pepper']);
expect(loadConfig({ ...base, HERMEVEN_AGENT_WAKE: 'friday' }).agents[0]!.wakeWords).toEqual(['friday']);
});
it('two agents may not answer to the same word', () => {
expect(() =>
loadConfig({ ...base, HERMEVEN_AGENT_NAME: 'Pepper', HERMEVEN_AGENTS: 'wendy', HERMEVEN_AGENT_WENDY_API_KEY: 'w'.repeat(24), HERMEVEN_AGENT_WENDY_WAKE: 'pepper' }),
).toThrow(ConfigError);
});
});