Files
hermeven/services/bridge/src/config.ts
T
DanandClaude Fable 5.2 e1d183b54d 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>
2026-11-28 10:52:06 -08:00

341 lines
15 KiB
TypeScript

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. */
id: string;
/** Shown on the glasses. */
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';
export interface BridgeConfig {
host: string;
port: number;
dbPath: string;
/** Exact browser origins allowed by CORS. Empty = no cross-origin browser access. */
allowedOrigins: string[];
/**
* Loopback hosts whose pages are allowed from ANY port (`http://127.0.0.1:*`). Needed because
* the Even phone app serves an installed app from `http://127.0.0.1:<port>` and picks a new
* port on every launch (observed on a real phone, 2026-11-21). Empty unless configured.
*/
allowedLoopbackAnyPort: string[];
/** Refuse to bind a non-loopback address without this (TLS must terminate in front). */
allowNonLoopback: boolean;
/** Trust X-Forwarded-For from a reverse proxy (only when one is actually in front). */
trustProxy: boolean;
hermes: {
/** Base URL of the Hermes API server, e.g. http://127.0.0.1:8642 or .../p/<profile>. */
baseUrl: string;
apiKey: string;
/** Label of the configured profile; devices are bound to it. Not sent to Hermes. */
profileLabel: string;
/** Per-request ephemeral instructions layered on the agent prompt. Empty disables. */
instructions: string;
pollIntervalMs: number;
requestTimeoutMs: number;
};
/**
* Every agent a paired device may talk to, default first. The list is the owner's allow-list:
* a client can only name an id from it. Each agent has its own Hermes address and its own key.
*/
agents: AgentConfig[];
stt: {
provider: 'none' | 'builtin' | 'openai-compatible';
baseUrl: string;
apiKey: string;
/** Bundled manifest name for `builtin`; provider model name for `openai-compatible`. */
model: string;
/** `builtin` only: the pinned artifacts to load, and the directory they are read from. */
manifest: ModelManifest | null;
modelDir: string;
};
limits: {
captureMaxSeconds: number;
transcribeDeadlineSeconds: number;
agentDeadlineSeconds: number;
approvalWaitSeconds: number;
cancelGraceSeconds: number;
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: {
tokenTtlSeconds: number;
pairingTtlSeconds: number;
pairingCodeTtlSeconds: number;
};
/** How long input/answer text stays in the bridge's result cache. Hermes is the authority. */
resultRetentionSeconds: number;
logLevel: string;
}
const DEFAULT_INSTRUCTIONS =
'The user reads this reply on a small monochrome heads-up display. ' +
'Answer in plain text without Markdown, tables, code fences or links. ' +
'Lead with the direct answer in one or two short sentences, then add detail only if it is needed.';
export class ConfigError extends Error {
override name = 'ConfigError';
}
function int(env: NodeJS.ProcessEnv, key: string, fallback: number, min = 1, max = Number.MAX_SAFE_INTEGER): number {
const raw = env[key];
if (raw === undefined || raw === '') return fallback;
const n = Number(raw);
if (!Number.isInteger(n) || n < min || n > max) {
throw new ConfigError(`${key} must be an integer between ${min} and ${max}`);
}
return n;
}
function bool(env: NodeJS.ProcessEnv, key: string, fallback = false): boolean {
const raw = env[key];
if (raw === undefined || raw === '') return fallback;
if (['1', 'true', 'yes'].includes(raw.toLowerCase())) return true;
if (['0', 'false', 'no'].includes(raw.toLowerCase())) return false;
throw new ConfigError(`${key} must be true or false`);
}
export function isLoopback(host: string): boolean {
return host === 'localhost' || host === '::1' || /^127\./.test(host);
}
function httpUrl(key: string, raw: string): string {
let url: URL;
try {
url = new URL(raw);
} catch {
throw new ConfigError(`${key} is not a valid URL`);
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new ConfigError(`${key} must be http(s)`);
if (url.protocol === 'http:' && !isLoopback(url.hostname)) {
throw new ConfigError(`${key} must use https outside loopback`);
}
return raw.replace(/\/+$/, '');
}
/** Manifests shipped with the bridge: `services/bridge/models/<name>.json`. */
export function bundledManifestPath(name: string): string {
return fileURLToPath(new URL(`../models/${name}.json`, import.meta.url));
}
function loadModelManifest(name: string, customPath: string | undefined): ModelManifest {
let path: string;
if (customPath) {
path = customPath;
} else {
if (!/^[a-z0-9][a-z0-9.-]*$/.test(name)) {
throw new ConfigError('STT_MODEL must be the name of a bundled pinned model (whisper-base, whisper-tiny)');
}
path = bundledManifestPath(name);
if (!existsSync(path)) {
throw new ConfigError(
`STT_MODEL "${name}" has no bundled pinned manifest. Use whisper-base or whisper-tiny, or point ` +
'STT_MODEL_MANIFEST at a manifest that pins a commit id and a SHA-256 for every file.',
);
}
}
try {
return validateManifest(JSON.parse(readFileSync(path, 'utf8')));
} catch (err) {
throw new ConfigError(`Speech model manifest could not be used: ${err instanceof Error ? err.message : 'unreadable'}`);
}
}
const AGENT_ID = /^[a-z][a-z0-9_-]{0,31}$/;
function agentName(key: string, raw: string | undefined, fallback: string): string {
const name = (raw ?? '').trim() || fallback;
if (name.length > 24 || /[\u0000-\u001f]/.test(name)) throw new ConfigError(`${key} must be at most 24 printable characters`);
return name;
}
/**
* The default agent is the Hermes API server at HERMES_BASE_URL with HERMES_API_KEY. Further
* agents are named in HERMEVEN_AGENTS (comma-separated ids) and are other profiles served by
* the same Hermes gateway under `/p/<profile>` (gateway.multiplex_profiles). Hermes gives each
* 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: 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(',')
.map((s) => s.trim())
.filter(Boolean);
for (const id of ids) {
if (!AGENT_ID.test(id)) throw new ConfigError('HERMEVEN_AGENTS entries must be lower-case ids (letters, digits, - and _)');
if (agents.some((a) => a.id === id)) throw new ConfigError(`HERMEVEN_AGENTS names "${id}" more than once (or uses the reserved id "default")`);
const prefix = `HERMEVEN_AGENT_${id.toUpperCase().replace(/-/g, '_')}`;
const apiKey = env[`${prefix}_API_KEY`] || '';
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`);
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;
}
export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
const host = env.HERMEVEN_HOST || '127.0.0.1';
const allowNonLoopback = bool(env, 'HERMEVEN_ALLOW_NON_LOOPBACK');
if (!isLoopback(host) && !allowNonLoopback) {
throw new ConfigError(
'HERMEVEN_HOST is not loopback. Put a TLS-terminating proxy or private network in front and set ' +
'HERMEVEN_ALLOW_NON_LOOPBACK=true to confirm.',
);
}
const hermesKey = env.HERMES_API_KEY || '';
if (!hermesKey) throw new ConfigError('HERMES_API_KEY is required (the Hermes API server refuses to start without one)');
const hermesBaseUrl = httpUrl('HERMES_BASE_URL', env.HERMES_BASE_URL || 'http://127.0.0.1:8642').replace(/\/+$/, '');
const originEntries = (env.HERMEVEN_ALLOWED_ORIGINS || '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
// The one permitted wildcard: any port on a loopback address, over plain http, written
// exactly as `http://127.0.0.1:*`, `http://localhost:*` or `http://[::1]:*`. A loopback
// origin can only be a page served on the same device as the browser making the request.
// No other wildcard exists: not for hosts, not for schemes, not for non-loopback ports.
const allowedLoopbackAnyPort: string[] = [];
const allowedOrigins: string[] = [];
for (const entry of originEntries) {
const anyPort = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\]):\*$/.exec(entry);
if (anyPort) allowedLoopbackAnyPort.push(anyPort[1]!);
else allowedOrigins.push(entry);
}
for (const origin of allowedOrigins) {
if (origin.includes('*')) {
throw new ConfigError(
'HERMEVEN_ALLOWED_ORIGINS must list exact origins. The only wildcard accepted is the port of a ' +
'loopback address, written http://127.0.0.1:* (or localhost, or [::1]).',
);
}
let parsed: URL;
try {
parsed = new URL(origin);
} catch {
throw new ConfigError(`HERMEVEN_ALLOWED_ORIGINS entry is not an origin: ${origin}`);
}
if (parsed.origin !== origin) throw new ConfigError(`HERMEVEN_ALLOWED_ORIGINS entry must be scheme://host[:port]: ${origin}`);
}
// Built-in Whisper is the default: voice works with no provider account and no audio
// leaving the bridge host.
const sttProvider = (env.STT_PROVIDER || 'builtin') as BridgeConfig['stt']['provider'];
if (sttProvider !== 'none' && sttProvider !== 'builtin' && sttProvider !== 'openai-compatible') {
throw new ConfigError('STT_PROVIDER must be "builtin", "openai-compatible" or "none"');
}
const sttModel = env.STT_MODEL || (sttProvider === 'builtin' ? 'whisper-base' : '');
// The built-in model is always pinned: a commit id plus a SHA-256 for every file. There is
// no unpinned mode. A model that is not bundled needs its own manifest file.
const sttManifest = sttProvider === 'builtin' ? loadModelManifest(sttModel, env.STT_MODEL_MANIFEST) : null;
let sttBaseUrl = '';
if (sttProvider === 'openai-compatible') {
if (!env.STT_BASE_URL) throw new ConfigError('STT_BASE_URL is required for STT_PROVIDER=openai-compatible');
if (!env.STT_MODEL) throw new ConfigError('STT_MODEL is required for STT_PROVIDER=openai-compatible');
sttBaseUrl = httpUrl('STT_BASE_URL', env.STT_BASE_URL);
}
const captureMaxSeconds = int(env, 'HERMEVEN_CAPTURE_MAX_SECONDS', DEFAULT_LIMITS.captureMaxSeconds, 1, 120);
return {
host,
port: int(env, 'HERMEVEN_PORT', 8787, 0, 65535),
dbPath: env.HERMEVEN_DB_PATH || './data/hermeven.sqlite',
allowedOrigins,
allowedLoopbackAnyPort,
allowNonLoopback,
trustProxy: bool(env, 'HERMEVEN_TRUST_PROXY'),
hermes: {
baseUrl: hermesBaseUrl,
apiKey: hermesKey,
profileLabel: env.HERMES_PROFILE_LABEL || 'default',
instructions: env.HERMEVEN_INSTRUCTIONS === undefined ? DEFAULT_INSTRUCTIONS : env.HERMEVEN_INSTRUCTIONS,
pollIntervalMs: int(env, 'HERMES_POLL_INTERVAL_MS', 150, 20, 10_000),
requestTimeoutMs: int(env, 'HERMES_REQUEST_TIMEOUT_MS', 10_000, 50, 120_000),
},
agents: agentsFromEnv(env, hermesBaseUrl, hermesKey),
stt: {
provider: sttProvider,
baseUrl: sttBaseUrl,
apiKey: env.STT_API_KEY || '',
model: sttModel,
manifest: sttManifest,
modelDir: env.STT_MODEL_DIR || './data/models',
},
limits: {
captureMaxSeconds,
transcribeDeadlineSeconds: int(env, 'HERMEVEN_TRANSCRIBE_DEADLINE_SECONDS', DEFAULT_LIMITS.transcribeDeadlineSeconds, 1, 300),
agentDeadlineSeconds: int(env, 'HERMEVEN_AGENT_DEADLINE_SECONDS', DEFAULT_LIMITS.agentDeadlineSeconds, 1, 3600),
approvalWaitSeconds: int(env, 'HERMEVEN_APPROVAL_WAIT_SECONDS', DEFAULT_LIMITS.approvalWaitSeconds, 1, 3600),
cancelGraceSeconds: int(env, 'HERMEVEN_CANCEL_GRACE_SECONDS', 30, 1, 600),
textMaxChars: DEFAULT_LIMITS.textMaxChars,
// 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: {
tokenTtlSeconds: int(env, 'HERMEVEN_TOKEN_TTL_SECONDS', 7 * 86_400, 60),
pairingTtlSeconds: int(env, 'HERMEVEN_PAIRING_TTL_SECONDS', 90 * 86_400, 60),
pairingCodeTtlSeconds: int(env, 'HERMEVEN_PAIRING_CODE_TTL_SECONDS', 300, 30, 3600),
},
resultRetentionSeconds: int(env, 'HERMEVEN_RESULT_RETENTION_SECONDS', 900, 10, 86_400),
logLevel: env.HERMEVEN_LOG_LEVEL || 'info',
};
}