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
+334 -10
View File
@@ -6,6 +6,7 @@ import { BODY_BOX, HUD, renderHud } from './hud.ts';
import { paginate, type MeasureLines } from './paginate.ts';
import { toPlainText } from './plaintext.ts';
import { currentAgent, initialState, reduce, type Agent, type AppEvent, type AppState, type Effect, type HudError } from './reducer.ts';
import { SpeechSegmenter, WAKE_SEGMENTER, type SegmenterOptions } from './vad.ts';
const STORAGE_KEY = 'hermeven.v1';
@@ -88,9 +89,38 @@ export interface Snapshot {
glassesInput: string;
/** Last settled turn, complete and untruncated, for the phone. */
lastTurn: TurnResult | null;
/**
* Hands free (listening for an agent's name). `available`: this build and this bridge can do
* it. `enabled`: that mode is the one in use. `listening`: the microphone is open for it now.
*/
wake: { available: boolean; enabled: boolean; listening: boolean };
log: DiagEntry[];
}
export interface WakeTiming {
/** After a name alone, a pause this long ends the question that follows. */
commandEndSilenceMs: number;
/** After a name alone, nothing said for this long: back to rest, nothing sent. */
armTimeoutMs: number;
/** No audio frames for this long while listening: the microphone is reopened. */
stallMs: number;
/** How long to wait before trying again after the microphone was refused or stayed silent. */
retryMs: number;
/** How often the microphone is checked on. */
watchMs: number;
/** After the bridge refused or could not be reached, speech is not sent for this long. */
pauseMs: number;
}
export const DEFAULT_WAKE_TIMING: WakeTiming = {
commandEndSilenceMs: 1200,
armTimeoutMs: 6000,
stallMs: 5000,
retryMs: 15_000,
watchMs: 2000,
pauseMs: 10_000,
};
export interface IdleExitMs {
/** An answer is on screen and has not been touched. Paging or any gesture restarts it. */
answer: number | null;
@@ -129,6 +159,18 @@ export interface ControllerOptions {
phoneGraceMs?: number;
/** A question asked after this long a silence starts a new conversation. */
conversationGapMs?: number;
/**
* Make hands-free mode possible: while it is in use the microphone is open whenever the app is
* at rest, listening for an agent's name ("Wendy, ..."), and the app does not leave the
* glasses by itself. Absent or `null`: there is no such mode and the microphone opens only on
* a tap.
*/
wake?: Partial<WakeTiming> | null;
/**
* Open on a menu (Hands free, Agents) instead of at Ready; double tap at Ready returns to it.
* Without it the app opens at Ready, in hands-free mode if `wake` is given.
*/
menu?: boolean;
/** If the host does not confirm the exit, try again after this long... */
exitRetryMs?: number;
/** ...up to this many attempts in a row. Any activity starts the count again. */
@@ -142,6 +184,11 @@ interface Capture {
maxBytes: number;
lastFrameAt: number;
limitSent: boolean;
/** Started by name: it ends when the speaker stops, and is given up if nobody speaks. */
auto: boolean;
startedAt: number;
/** The whole question was already spoken before the recording began: send it as it is. */
complete: boolean;
}
type PendingInput = { requestId: string; kind: 'text'; text: string } | { requestId: string; kind: 'audio'; pcm: Uint8Array };
@@ -206,6 +253,25 @@ export class Controller {
/** Set while a long press that STARTED a recording is still held down. */
private heldPress: { generation: number; at: number } | null = null;
// ---- listening for a name (all unused when `wake` is null)
private readonly wake: WakeTiming | null;
private readonly segmenter = new SpeechSegmenter();
/** Every microphone open and close in wake mode goes through this, one after another. */
private micChain: Promise<void> = Promise.resolve();
private micRestart = false;
/** A stretch of speech is at the bridge being checked for a name. One at a time. */
private wakeChecking = false;
/** The latest stretch of speech that ended while a check was still out. */
private wakeBacklog: Uint8Array | null = null;
private wakePausedUntil = 0;
/** The bridge said it has no wake names (or is too old): stop asking for this session. */
private wakeUnsupported = false;
private wakeFrameAt = 0;
private wakeRetryAt = 0;
/** Already noted, so a repeated refusal or stall is logged once per streak. */
private wakeTrouble = false;
private wakeWatch: ReturnType<typeof setInterval> | null = null;
constructor(private readonly options: ControllerOptions) {
this.device = options.device;
this.now = options.now ?? Date.now;
@@ -220,6 +286,7 @@ export class Controller {
this.conversationGapMs = options.conversationGapMs ?? 10 * 60_000;
this.exitRetryMs = options.exitRetryMs ?? 3_000;
this.exitAttempts = Math.max(1, options.exitAttempts ?? 4);
this.wake = options.wake ? { ...DEFAULT_WAKE_TIMING, ...options.wake } : null;
}
// ------------------------------------------------------------------ public
@@ -290,8 +357,184 @@ export class Controller {
storageFault: this.storageFault,
agents,
agentId: this.stored?.agentId ?? null,
menu: this.options.menu === true,
handsFree: this.handsFreeAvailable(),
});
if (abandoned) void this.cancelTurn(abandoned);
if (this.wake) this.wakeWatch = setInterval(() => this.watchWakeMic(), this.wake.watchMs);
}
// ------------------------------------------------------- listening for a name
/** This build has hands free, and nothing has said the bridge cannot do it. */
private handsFreeAvailable(): boolean {
return this.wake !== null && !this.wakeUnsupported && this.status?.stt_configured !== false;
}
/** Hands-free mode is the one in use. While true the app stays open. */
private wakeOn(): boolean {
return this.handsFreeAvailable() && this.stored !== null && this.state.mode === 'handsfree';
}
/** Right now the microphone should be open, listening for a name. Only ever at rest. */
private wakeActive(): boolean {
return (
this.wakeOn() && this.client !== null && this.hudReady && !this.stopped && !this.exited && !this.leaving && RESTING.has(this.state.phase)
);
}
private wakeSegmenter(endSilenceMs = WAKE_SEGMENTER.endSilenceMs): SegmenterOptions {
return { ...WAKE_SEGMENTER, endSilenceMs, maxMs: this.state.captureMaxSeconds * 1000 };
}
/** Wake mode: after anything that may change whether the microphone should be open. */
private afterChange(): void {
if (!this.wake) return;
if (this.capture?.auto) {
// The segmenter is following the recording that a name started.
} else if (this.wakeActive() && !this.capture) {
this.segmenter.configure(this.wakeSegmenter());
} else {
// Not listening: nothing half-heard is kept for later.
this.segmenter.reset();
this.wakeBacklog = null;
}
void this.syncMic();
}
/**
* Wake mode: bring the microphone to where it should be now (open for a recording or for
* listening, otherwise closed). Runs strictly one after another, and looks at what is wanted
* when its turn comes, so a burst of changes always ends in the right place. Resolves to
* whether the microphone is open.
*/
private syncMic(): Promise<boolean> {
const run = this.micChain.then(async () => {
if (this.micRestart && this.micOpen) {
this.micOpen = false;
await this.device.stopMic();
}
this.micRestart = false;
const want = !this.stopped && (this.capture !== null || this.wakeActive());
if (want && !this.micOpen) {
// A refused microphone is not asked for again at every turn of the app, only by the
// periodic check. A recording the user asked for always tries.
if (this.capture !== null || this.now() >= this.wakeRetryAt) {
this.micOpen = true;
const ok = await this.device.startMic();
if (ok) {
this.wakeFrameAt = this.now();
} else {
this.micOpen = false;
this.wakeRetryAt = this.now() + this.wake!.retryMs;
if (!this.wakeTrouble) this.note('wake', 'the microphone could not be opened; will keep trying');
this.wakeTrouble = true;
}
}
} else if (!want && this.micOpen) {
this.micOpen = false;
await this.device.stopMic();
}
const listening = this.micOpen && this.wakeActive();
if (listening !== this.state.wakeListening) this.dispatch({ type: 'wake_status', listening });
return this.micOpen;
});
this.micChain = run.then(
() => undefined,
() => undefined,
);
return run.catch(() => false);
}
/** Periodic: a listening microphone that has gone quiet, or was refused, is opened again. */
private watchWakeMic(): void {
if (!this.wake || this.capture || !this.wakeActive()) return;
if (!this.micOpen) {
if (this.now() >= this.wakeRetryAt) void this.syncMic();
return;
}
if (this.now() - this.wakeFrameAt <= this.wake.stallMs) return;
// A suspended page or a dropped stream both look like silence on the wire.
if (!this.wakeTrouble) this.note('wake', 'no audio frames while listening; reopening the microphone');
this.wakeTrouble = true;
this.micRestart = true;
this.wakeFrameAt = this.now() + this.wake.retryMs - this.wake.stallMs;
void this.syncMic();
}
private onWakeAudio(pcm: Uint8Array): void {
this.wakeFrameAt = this.now();
this.wakeTrouble = false;
for (const event of this.segmenter.push(pcm)) {
if (event.type !== 'end') continue;
if (this.wakeChecking) this.wakeBacklog = event.pcm;
else void this.checkWake(event.pcm);
}
}
/** Ask the bridge whether this stretch of speech began with an agent's name. */
private async checkWake(pcm: Uint8Array): Promise<void> {
const client = this.client;
if (!client || this.wakeChecking || this.now() < this.wakePausedUntil) return;
this.wakeChecking = true;
const generation = this.state.generation;
let matched = false;
try {
const result = await client.wake({ pcm, locale: this.options.locale });
// Anything the user did meanwhile (a tap, a cancel, a new pairing) wins over what was heard.
if (this.stale(generation) || this.client !== client || !this.wakeActive()) return;
if (result.matched && result.agent_id) {
matched = true;
this.onWake(result.agent_id, result.text);
} else if (result.near_miss) {
// The one place a spoken word reaches Diagnostics: a single word that was nearly a
// name, so that an alias can be added for it on the bridge.
this.note('wake', `heard "${result.near_miss}", which is close to an agent's name but not one`);
this.emit();
}
} catch (err) {
if (err instanceof BridgeApiError && err.body.code === 'not_found') {
this.wakeUnsupported = true;
this.note('wake', 'this bridge has no agent that can be called by name; hands free is not available');
this.dispatch({ type: 'handsfree_lost' });
} else {
this.note('wake', `check failed: ${describe(err)}`);
this.wakePausedUntil = this.now() + this.wake!.pauseMs;
if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
}
} finally {
this.wakeChecking = false;
}
// Something else was said while that check was out: it gets its own check, unless it was
// already used as the question that followed a name.
const next = this.wakeBacklog;
this.wakeBacklog = null;
if (next && !matched && !this.stale(generation) && this.wakeActive()) void this.checkWake(next);
}
/** An agent was called by name. `text` is what followed in the same breath, if anything. */
private onWake(agentId: string, text: string): void {
if (!this.stored) return;
const offered = this.state.agents;
// With no choice on offer there is only the default agent, and nothing about agents is sent.
if (offered.length === 0 ? agentId !== DEFAULT_AGENT : !offered.some((a) => a.id === agentId)) return;
const target = offered.length === 0 ? null : agentId;
const switching = target !== null && target !== currentAgent(this.state)?.id;
if (switching) this.swapStoredAgent(agentId);
let conversationId = switching ? this.stored.conversationId : this.state.conversationId;
// The app now stays open, so "a while since the last question" is checked here too, not
// only when the app starts.
if (conversationId && this.stored.lastTurnAt !== undefined && this.now() - this.stored.lastTurnAt > this.conversationGapMs) {
this.note('conversation', 'last question was a while ago: this one starts a new conversation');
conversationId = null;
this.stored = { ...this.stored, conversationId: null };
}
void this.save();
this.note('wake', `${agentId} was called by name${text ? '' : ' (name only: recording the question)'}`);
const freshId = this.newId();
this.dispatch(
text ? { type: 'wake_text', freshId, agentId: target, conversationId, text } : { type: 'wake_listen', freshId, agentId: target, conversationId },
);
}
// ------------------------------------------------------------------ agents
@@ -394,6 +637,8 @@ export class Controller {
for (const off of this.unsubscribers.splice(0)) off();
if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = null;
if (this.wakeWatch) clearInterval(this.wakeWatch);
this.wakeWatch = null;
this.stopTicker();
await this.closeMic();
}
@@ -411,6 +656,11 @@ export class Controller {
launchSource: this.launchSource,
glassesInput: this.device.inputSummary?.() ?? '',
lastTurn: this.lastTurn,
wake: {
available: this.handsFreeAvailable(),
enabled: this.wakeOn(),
listening: this.state.wakeListening,
},
log: [...this.log],
};
}
@@ -453,7 +703,17 @@ export class Controller {
this.note('bridge', `status check failed: ${describe(err)}`);
}
const agents = await this.loadAgents();
this.dispatch({ type: 'init', paired: true, conversationId: null, captureMaxSeconds, resumeRequestId: null, agents, agentId: null });
this.dispatch({
type: 'init',
paired: true,
conversationId: null,
captureMaxSeconds,
resumeRequestId: null,
agents,
agentId: null,
menu: this.options.menu === true,
handsFree: this.handsFreeAvailable(),
});
}
/** Disconnect: revoke the credential on the bridge, then clear everything held locally. */
@@ -520,6 +780,7 @@ export class Controller {
this.reconcileRemovedAgent();
if (before.phase !== step.state.phase) this.note('state', `${before.phase} -> ${step.state.phase}`);
for (const effect of step.effects) void this.run(effect);
this.afterChange();
this.render();
this.emit();
this.scheduleIdleExit();
@@ -546,11 +807,13 @@ export class Controller {
this.activityEpoch += 1;
}
if (this.stopped || this.exited || !this.idleExitMs || !this.hudReady) return;
// Listening for a name is the point of staying open: the app does not leave by itself.
if (this.wakeOn()) return;
const phase = this.state.phase;
const wait =
phase === 'answer'
? this.idleExitMs.answer
: phase === 'ready'
: phase === 'ready' || phase === 'menu'
? this.idleExitMs.ready
: phase === 'error' || phase === 'cancelled'
? this.idleExitMs.message
@@ -598,6 +861,7 @@ export class Controller {
// that changed no state, or a touch on the phone page), that activity already restarted the
// full countdown or the phone grace period, and that timer stands: no short retry replaces
// it. Otherwise try again, a bounded number of times.
this.afterChange();
if (this.activityEpoch !== epoch) return;
this.exitFailures += 1;
if (this.exitFailures >= this.exitAttempts) {
@@ -616,7 +880,7 @@ export class Controller {
try {
switch (effect.type) {
case 'start_capture':
return await this.startCapture(effect.generation);
return await this.startCapture(effect.generation, effect.auto === true && this.wake !== null);
case 'stop_capture_and_submit':
return await this.stopCaptureAndSubmit(effect.generation, effect.requestId);
case 'discard_capture':
@@ -642,7 +906,7 @@ export class Controller {
}
}
private async startCapture(generation: number): Promise<void> {
private async startCapture(generation: number, auto = false): Promise<void> {
const capture: Capture = {
generation,
chunks: [],
@@ -650,36 +914,72 @@ export class Controller {
maxBytes: this.state.captureMaxSeconds * AUDIO_FORMAT.bytesPerSecond,
lastFrameAt: this.now(),
limitSent: false,
auto,
startedAt: this.now(),
complete: false,
};
if (auto) {
// The name was recognised a moment after it was said, and the speaker may not have
// waited: whatever has been said since belongs to this question.
for (const heard of [this.wakeBacklog, this.segmenter.buffered()]) {
const room = capture.maxBytes - capture.bytes;
if (!heard || heard.length === 0 || room <= 0) continue;
const chunk = heard.length > room ? heard.slice(0, room - (room % 2)) : heard;
capture.chunks.push(chunk);
capture.bytes += chunk.length;
}
capture.complete = this.wakeBacklog !== null && !this.segmenter.speaking;
this.wakeBacklog = null;
this.segmenter.configure(this.wakeSegmenter(this.wake!.commandEndSilenceMs));
}
this.capture = capture;
this.micOpen = true;
const ok = await this.device.startMic();
let ok: boolean;
if (this.wake) {
ok = await this.syncMic();
} else {
this.micOpen = true;
ok = await this.device.startMic();
}
if (this.capture !== capture || this.stale(generation)) {
// Cancelled while the microphone was opening. Stop unconditionally unless a newer
// capture now owns the microphone: a stop that turns out to be redundant is harmless.
if (!this.capture || this.capture === capture) {
this.capture = null;
this.micOpen = false;
this.stopTicker();
await this.device.stopMic();
if (this.wake) {
await this.syncMic();
} else {
this.micOpen = false;
await this.device.stopMic();
}
}
return;
}
if (!ok) {
this.capture = null;
this.micOpen = false;
if (!this.wake) this.micOpen = false;
this.dispatch({ type: 'capture_failed', generation, reason: 'mic_refused' });
return;
}
capture.lastFrameAt = this.now();
this.dispatch({ type: 'capture_started', generation, at: this.now() });
this.startTicker();
if (capture.complete && !capture.limitSent) {
capture.limitSent = true;
this.dispatch({ type: 'capture_limit', generation });
}
}
private onAudio(pcm: Uint8Array): void {
const capture = this.capture;
if (!capture) {
// No recording: while listening for a name the frame goes to the speech detector.
// Otherwise it is dropped on the floor.
if (this.wake && this.micOpen && this.wakeActive()) this.onWakeAudio(pcm);
return;
}
// Frames outside an active, current-generation capture are dropped on the floor.
if (!capture || capture.generation !== this.state.generation || this.state.phase !== 'listening') return;
if (capture.generation !== this.state.generation || this.state.phase !== 'listening') return;
capture.lastFrameAt = this.now();
const room = capture.maxBytes - capture.bytes;
if (room > 0) {
@@ -692,6 +992,23 @@ export class Controller {
this.note('capture', 'capture limit reached');
this.dispatch({ type: 'capture_limit', generation: capture.generation });
}
if (capture.auto && !capture.limitSent) this.followAutoCapture(capture, pcm);
}
/** A recording started by name: send when the speaker stops, give up if nobody speaks. */
private followAutoCapture(capture: Capture, pcm: Uint8Array): void {
for (const event of this.segmenter.push(pcm)) {
if (event.type !== 'end') continue;
capture.limitSent = true;
this.note('capture', 'the speaker stopped');
this.dispatch({ type: 'capture_limit', generation: capture.generation });
return;
}
if (!this.segmenter.speaking && this.now() - capture.startedAt > this.wake!.armTimeoutMs) {
capture.limitSent = true;
this.note('capture', 'nothing was said after the name');
this.dispatch({ type: 'capture_abandoned', generation: capture.generation });
}
}
private async stopCaptureAndSubmit(generation: number, requestId: string): Promise<void> {
@@ -718,6 +1035,12 @@ export class Controller {
}
private async closeMic(): Promise<void> {
if (this.wake) {
// Wake mode: "close" means "put it where it should be", which at rest is open.
this.stopTicker();
await this.syncMic();
return;
}
if (!this.micOpen) return;
this.micOpen = false;
this.stopTicker();
@@ -1008,6 +1331,7 @@ export class Controller {
case 'foreground_exit':
// Also fired when the OS menu opens and closes; nothing is torn down here.
this.note('lifecycle', event.type);
this.afterChange();
return this.render();
}
}