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:
@@ -17,7 +17,7 @@ the implementer read from the server's log, and what Cody reproduced independent
|
|||||||
| Path | State |
|
| Path | State |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Client, bridge and contract | Implemented. |
|
| Client, bridge and contract | Implemented. |
|
||||||
| Automated tests with fakes (299) | Passing. |
|
| Automated tests with fakes (341) | Passing. |
|
||||||
| Client in Even's official simulator | Passing (7 scenarios). Simulator only. |
|
| Client in Even's official simulator | Passing (7 scenarios). Simulator only. |
|
||||||
| Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. |
|
| Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. |
|
||||||
| Built-in speech-to-text (Whisper, in the bridge) | Passing (11 scenarios) on a real speech recording, including with no network. Not yet on audio from the glasses. |
|
| Built-in speech-to-text (Whisper, in the bridge) | Passing (11 scenarios) on a real speech recording, including with no network. Not yet on audio from the glasses. |
|
||||||
@@ -29,6 +29,7 @@ the implementer read from the server's log, and what Cody reproduced independent
|
|||||||
| Locked phone | First success on 2026-11-21 with the beta build: launched by voice ("Hey Even, open Pepper") and a spoken question answered with the phone locked (Dan's report). The specification's ten-cycle acceptance run has **not** been done. |
|
| Locked phone | First success on 2026-11-21 with the beta build: launched by voice ("Hey Even, open Pepper") and a spoken question answered with the phone locked (Dan's report). The specification's ten-cycle acceptance run has **not** been done. |
|
||||||
| Leaving the glasses when idle | 0.1.1 on the device (2026-11-21, Dan's report): after one gesture the app left by itself and Telegram notifications returned to the lenses; after a voice launch with nothing touched it did **not** leave. 0.1.2 starts the countdown however the app was opened; tested with fakes and the simulator, **not installed on the device.** |
|
| Leaving the glasses when idle | 0.1.1 on the device (2026-11-21, Dan's report): after one gesture the app left by itself and Telegram notifications returned to the lenses; after a voice launch with nothing touched it did **not** leave. 0.1.2 starts the countdown however the app was opened; tested with fakes and the simulator, **not installed on the device.** |
|
||||||
| More than one agent (swipe at Ready to choose) | 0.2.0. Deployed on 2026-11-22 with three agents; a question sent through the bridge was answered by a second Hermes profile (`docs/evidence/droplet/2026-11-21.md`). Installed on the device and tried by Dan, who reported "All tests check out" without detail (`docs/evidence/device/2026-11-21.md`, sixth session). The agent screens have not been run in the simulator. |
|
| More than one agent (swipe at Ready to choose) | 0.2.0. Deployed on 2026-11-22 with three agents; a question sent through the bridge was answered by a second Hermes profile (`docs/evidence/droplet/2026-11-21.md`). Installed on the device and tried by Dan, who reported "All tests check out" without detail (`docs/evidence/device/2026-11-21.md`, sixth session). The agent screens have not been run in the simulator. |
|
||||||
|
| Opening menu (Hands free, Agents); hands-free mode: calling an agent by name ("Wendy, ...") | 0.3.0. Automated tests with fakes only (a tone for speech, a scripted recogniser). **Not run in the simulator, not deployed, not on the device.** The speech detector's thresholds are untested guesses. `docs/decisions/0004-always-listening.md`. |
|
||||||
| Real tools and approval flow | One tool use seen (a Telegram message, reported by Dan). The approval path has **not** been exercised against a real agent. |
|
| Real tools and approval flow | One tool use seen (a Telegram message, reported by Dan). The approval path has **not** been exercised against a real agent. |
|
||||||
| Sustained load, backups, monitoring, upgrades on the server | **Not verified.** |
|
| Sustained load, backups, monitoring, upgrades on the server | **Not verified.** |
|
||||||
| Clean-host install (`deploy/install.sh`) | Proven on a disposable Ubuntu 24.04 container with systemd (`tests/deploy/runbook-proof.sh`), not on a second real server. |
|
| Clean-host install (`deploy/install.sh`) | Proven on a disposable Ubuntu 24.04 container with systemd (`tests/deploy/runbook-proof.sh`), not on a second real server. |
|
||||||
@@ -73,14 +74,16 @@ instructions, including building for the glasses, are in `docs/setup.md`.
|
|||||||
|
|
||||||
| You do | It does |
|
| You do | It does |
|
||||||
|---|---|
|
|---|---|
|
||||||
|
| Open the app | From 0.3.0: a menu. Swipe to move, tap to open. **Hands free** is first, **Agents** (everything below, as before) second. |
|
||||||
|
| In Hands free: say an agent's name, then your question | The microphone is open while the app is at rest (the status line starts with `●`). "Wendy, what's on my calendar" goes to Wendy. A name alone starts a recording that is sent when you stop speaking. Tap and swipe still work. The app stays on the glasses. |
|
||||||
| Tap | Start recording. The display shows `● REC` and a timer the whole time. |
|
| Tap | Start recording. The display shows `● REC` and a timer the whole time. |
|
||||||
| Tap again | Stop and send. Recording also stops by itself after 30 seconds. |
|
| Tap again | Stop and send. Recording also stops by itself after 30 seconds. |
|
||||||
| Hold, speak, release | Push-to-talk: recording starts when the glasses register the hold and is sent when you let go. A hold released in under 0.7 s behaves like a tap. |
|
| Hold, speak, release | Push-to-talk: recording starts when the glasses register the hold and is sent when you let go. A hold released in under 0.7 s behaves like a tap. |
|
||||||
| Swipe down / up | Next / previous page of the answer. |
|
| Swipe down / up | Next / previous page of the answer. |
|
||||||
| Tap on an answer | Ask a follow-up in the same conversation. |
|
| Tap on an answer | Ask a follow-up in the same conversation. |
|
||||||
| Double tap | Cancel what is in progress, or go back. At "Ready" it opens the system exit dialog. |
|
| Double tap | Cancel what is in progress, or go back. At "Ready" it returns to the menu (closing the microphone if it was hands free); on the menu it opens the system exit dialog. |
|
||||||
| Swipe at Ready | From 0.2.0, when the bridge offers more than one agent: choose who to talk to. The name is shown; on an answer a swipe still turns the page. |
|
| Swipe at Ready | From 0.2.0, when the bridge offers more than one agent: choose who to talk to. The name is shown; on an answer a swipe still turns the page. |
|
||||||
| Leave it alone | From 0.1.1: Pepper leaves the glasses by herself (20 s after an answer, 30 s at Ready, 10 s after an error), so the normal screen and notifications return. Call her back from the glasses' menu or with "Hey Even, open Pepper". |
|
| Leave it alone | In Hands free the app stays open. On the menu and in Agents, as from 0.1.1: Pepper leaves the glasses by herself (20 s after an answer, 30 s at Ready, 10 s after an error), so the normal screen and notifications return. Call her back from the glasses' menu or with "Hey Even, open Pepper". |
|
||||||
| Tap, then long press | The system menu, with "New conversation" and "Cancel request". |
|
| Tap, then long press | The system menu, with "New conversation" and "Cancel request". |
|
||||||
|
|
||||||
Cancelling stops the agent as soon as Hermes can; it does not undo anything the agent already did.
|
Cancelling stops the agent as soon as Hermes can; it does not undo anything the agent already did.
|
||||||
@@ -120,6 +123,6 @@ What each suite does and does not show is in `docs/test-evidence.md`.
|
|||||||
|
|
||||||
## Not in this slice
|
## Not in this slice
|
||||||
|
|
||||||
Wake words, always-on listening, choosing an agent by saying its name, camera features,
|
On-device wake-word detection (names are recognised on the bridge), camera features,
|
||||||
text-to-speech, billing, store launch, and running alongside Even's native captions (the public
|
text-to-speech, billing, store launch, and running alongside Even's native captions (the public
|
||||||
SDK does not offer it).
|
SDK does not offer it).
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"package_id": "xylo.hermeven",
|
"package_id": "xylo.hermeven",
|
||||||
"edition": "202601",
|
"edition": "202601",
|
||||||
"name": "Pepper",
|
"name": "Pepper",
|
||||||
"version": "0.2.0",
|
"version": "0.3.0",
|
||||||
"min_sdk_version": "0.0.16",
|
"min_sdk_version": "0.0.16",
|
||||||
"entrypoint": "index.html",
|
"entrypoint": "index.html",
|
||||||
"permissions": [
|
"permissions": [
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "g2-microphone",
|
"name": "g2-microphone",
|
||||||
"desc": "Records your question from the glasses microphone, only while you have tapped to ask."
|
"desc": "Records your question from the glasses microphone when you tap to ask. In hands-free mode, which you choose on the opening menu, it listens while the app is open for an agent's name and your question."
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"supported_languages": ["en"]
|
"supported_languages": ["en"]
|
||||||
|
|||||||
@@ -31,6 +31,10 @@ export interface BootOptions {
|
|||||||
dev?: boolean;
|
dev?: boolean;
|
||||||
/** `false` keeps the app on the glasses indefinitely; an object overrides the times. Both are for automated simulator runs. */
|
/** `false` keeps the app on the glasses indefinitely; an object overrides the times. Both are for automated simulator runs. */
|
||||||
idleExit?: boolean | Partial<IdleExitMs>;
|
idleExit?: boolean | Partial<IdleExitMs>;
|
||||||
|
/** `false` removes hands-free mode (the microphone then opens only on a tap). */
|
||||||
|
wake?: boolean;
|
||||||
|
/** `false` opens at Ready instead of on the menu. For automated simulator runs. */
|
||||||
|
menu?: boolean;
|
||||||
/** Reload hook, replaceable in tests. */
|
/** Reload hook, replaceable in tests. */
|
||||||
reload?: () => void;
|
reload?: () => void;
|
||||||
}
|
}
|
||||||
@@ -92,6 +96,9 @@ export async function boot(doc: Document, win: Window, options: BootOptions = {}
|
|||||||
measure: (text, width) => measureTextWrap(text, width).lineCount,
|
measure: (text, width) => measureTextWrap(text, width).lineCount,
|
||||||
locale: win.navigator.language || 'en-US',
|
locale: win.navigator.language || 'en-US',
|
||||||
onChange: (snapshot) => update(snapshot),
|
onChange: (snapshot) => update(snapshot),
|
||||||
|
// Hands free needs the glasses' microphone: never in the browser preview.
|
||||||
|
wake: mode === 'even' && options.wake !== false ? {} : null,
|
||||||
|
menu: options.menu !== false,
|
||||||
...(options.idleExit === false ? { idleExit: null } : typeof options.idleExit === 'object' ? { idleExit: options.idleExit } : {}),
|
...(options.idleExit === false ? { idleExit: null } : typeof options.idleExit === 'object' ? { idleExit: options.idleExit } : {}),
|
||||||
// Development builds mirror diagnostics to the console (visible in the simulator and the
|
// Development builds mirror diagnostics to the console (visible in the simulator and the
|
||||||
// Even dev console). Diagnostics never contain questions, answers or credentials.
|
// Even dev console). Diagnostics never contain questions, answers or credentials.
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { BODY_BOX, HUD, renderHud } from './hud.ts';
|
|||||||
import { paginate, type MeasureLines } from './paginate.ts';
|
import { paginate, type MeasureLines } from './paginate.ts';
|
||||||
import { toPlainText } from './plaintext.ts';
|
import { toPlainText } from './plaintext.ts';
|
||||||
import { currentAgent, initialState, reduce, type Agent, type AppEvent, type AppState, type Effect, type HudError } from './reducer.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';
|
const STORAGE_KEY = 'hermeven.v1';
|
||||||
|
|
||||||
@@ -88,9 +89,38 @@ export interface Snapshot {
|
|||||||
glassesInput: string;
|
glassesInput: string;
|
||||||
/** Last settled turn, complete and untruncated, for the phone. */
|
/** Last settled turn, complete and untruncated, for the phone. */
|
||||||
lastTurn: TurnResult | null;
|
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[];
|
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 {
|
export interface IdleExitMs {
|
||||||
/** An answer is on screen and has not been touched. Paging or any gesture restarts it. */
|
/** An answer is on screen and has not been touched. Paging or any gesture restarts it. */
|
||||||
answer: number | null;
|
answer: number | null;
|
||||||
@@ -129,6 +159,18 @@ export interface ControllerOptions {
|
|||||||
phoneGraceMs?: number;
|
phoneGraceMs?: number;
|
||||||
/** A question asked after this long a silence starts a new conversation. */
|
/** A question asked after this long a silence starts a new conversation. */
|
||||||
conversationGapMs?: number;
|
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... */
|
/** If the host does not confirm the exit, try again after this long... */
|
||||||
exitRetryMs?: number;
|
exitRetryMs?: number;
|
||||||
/** ...up to this many attempts in a row. Any activity starts the count again. */
|
/** ...up to this many attempts in a row. Any activity starts the count again. */
|
||||||
@@ -142,6 +184,11 @@ interface Capture {
|
|||||||
maxBytes: number;
|
maxBytes: number;
|
||||||
lastFrameAt: number;
|
lastFrameAt: number;
|
||||||
limitSent: boolean;
|
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 };
|
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. */
|
/** Set while a long press that STARTED a recording is still held down. */
|
||||||
private heldPress: { generation: number; at: number } | null = null;
|
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) {
|
constructor(private readonly options: ControllerOptions) {
|
||||||
this.device = options.device;
|
this.device = options.device;
|
||||||
this.now = options.now ?? Date.now;
|
this.now = options.now ?? Date.now;
|
||||||
@@ -220,6 +286,7 @@ export class Controller {
|
|||||||
this.conversationGapMs = options.conversationGapMs ?? 10 * 60_000;
|
this.conversationGapMs = options.conversationGapMs ?? 10 * 60_000;
|
||||||
this.exitRetryMs = options.exitRetryMs ?? 3_000;
|
this.exitRetryMs = options.exitRetryMs ?? 3_000;
|
||||||
this.exitAttempts = Math.max(1, options.exitAttempts ?? 4);
|
this.exitAttempts = Math.max(1, options.exitAttempts ?? 4);
|
||||||
|
this.wake = options.wake ? { ...DEFAULT_WAKE_TIMING, ...options.wake } : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ public
|
// ------------------------------------------------------------------ public
|
||||||
@@ -290,8 +357,184 @@ export class Controller {
|
|||||||
storageFault: this.storageFault,
|
storageFault: this.storageFault,
|
||||||
agents,
|
agents,
|
||||||
agentId: this.stored?.agentId ?? null,
|
agentId: this.stored?.agentId ?? null,
|
||||||
|
menu: this.options.menu === true,
|
||||||
|
handsFree: this.handsFreeAvailable(),
|
||||||
});
|
});
|
||||||
if (abandoned) void this.cancelTurn(abandoned);
|
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
|
// ------------------------------------------------------------------ agents
|
||||||
@@ -394,6 +637,8 @@ export class Controller {
|
|||||||
for (const off of this.unsubscribers.splice(0)) off();
|
for (const off of this.unsubscribers.splice(0)) off();
|
||||||
if (this.idleTimer) clearTimeout(this.idleTimer);
|
if (this.idleTimer) clearTimeout(this.idleTimer);
|
||||||
this.idleTimer = null;
|
this.idleTimer = null;
|
||||||
|
if (this.wakeWatch) clearInterval(this.wakeWatch);
|
||||||
|
this.wakeWatch = null;
|
||||||
this.stopTicker();
|
this.stopTicker();
|
||||||
await this.closeMic();
|
await this.closeMic();
|
||||||
}
|
}
|
||||||
@@ -411,6 +656,11 @@ export class Controller {
|
|||||||
launchSource: this.launchSource,
|
launchSource: this.launchSource,
|
||||||
glassesInput: this.device.inputSummary?.() ?? '',
|
glassesInput: this.device.inputSummary?.() ?? '',
|
||||||
lastTurn: this.lastTurn,
|
lastTurn: this.lastTurn,
|
||||||
|
wake: {
|
||||||
|
available: this.handsFreeAvailable(),
|
||||||
|
enabled: this.wakeOn(),
|
||||||
|
listening: this.state.wakeListening,
|
||||||
|
},
|
||||||
log: [...this.log],
|
log: [...this.log],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -453,7 +703,17 @@ export class Controller {
|
|||||||
this.note('bridge', `status check failed: ${describe(err)}`);
|
this.note('bridge', `status check failed: ${describe(err)}`);
|
||||||
}
|
}
|
||||||
const agents = await this.loadAgents();
|
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. */
|
/** Disconnect: revoke the credential on the bridge, then clear everything held locally. */
|
||||||
@@ -520,6 +780,7 @@ export class Controller {
|
|||||||
this.reconcileRemovedAgent();
|
this.reconcileRemovedAgent();
|
||||||
if (before.phase !== step.state.phase) this.note('state', `${before.phase} -> ${step.state.phase}`);
|
if (before.phase !== step.state.phase) this.note('state', `${before.phase} -> ${step.state.phase}`);
|
||||||
for (const effect of step.effects) void this.run(effect);
|
for (const effect of step.effects) void this.run(effect);
|
||||||
|
this.afterChange();
|
||||||
this.render();
|
this.render();
|
||||||
this.emit();
|
this.emit();
|
||||||
this.scheduleIdleExit();
|
this.scheduleIdleExit();
|
||||||
@@ -546,11 +807,13 @@ export class Controller {
|
|||||||
this.activityEpoch += 1;
|
this.activityEpoch += 1;
|
||||||
}
|
}
|
||||||
if (this.stopped || this.exited || !this.idleExitMs || !this.hudReady) return;
|
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 phase = this.state.phase;
|
||||||
const wait =
|
const wait =
|
||||||
phase === 'answer'
|
phase === 'answer'
|
||||||
? this.idleExitMs.answer
|
? this.idleExitMs.answer
|
||||||
: phase === 'ready'
|
: phase === 'ready' || phase === 'menu'
|
||||||
? this.idleExitMs.ready
|
? this.idleExitMs.ready
|
||||||
: phase === 'error' || phase === 'cancelled'
|
: phase === 'error' || phase === 'cancelled'
|
||||||
? this.idleExitMs.message
|
? 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
|
// 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
|
// full countdown or the phone grace period, and that timer stands: no short retry replaces
|
||||||
// it. Otherwise try again, a bounded number of times.
|
// it. Otherwise try again, a bounded number of times.
|
||||||
|
this.afterChange();
|
||||||
if (this.activityEpoch !== epoch) return;
|
if (this.activityEpoch !== epoch) return;
|
||||||
this.exitFailures += 1;
|
this.exitFailures += 1;
|
||||||
if (this.exitFailures >= this.exitAttempts) {
|
if (this.exitFailures >= this.exitAttempts) {
|
||||||
@@ -616,7 +880,7 @@ export class Controller {
|
|||||||
try {
|
try {
|
||||||
switch (effect.type) {
|
switch (effect.type) {
|
||||||
case 'start_capture':
|
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':
|
case 'stop_capture_and_submit':
|
||||||
return await this.stopCaptureAndSubmit(effect.generation, effect.requestId);
|
return await this.stopCaptureAndSubmit(effect.generation, effect.requestId);
|
||||||
case 'discard_capture':
|
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 = {
|
const capture: Capture = {
|
||||||
generation,
|
generation,
|
||||||
chunks: [],
|
chunks: [],
|
||||||
@@ -650,36 +914,72 @@ export class Controller {
|
|||||||
maxBytes: this.state.captureMaxSeconds * AUDIO_FORMAT.bytesPerSecond,
|
maxBytes: this.state.captureMaxSeconds * AUDIO_FORMAT.bytesPerSecond,
|
||||||
lastFrameAt: this.now(),
|
lastFrameAt: this.now(),
|
||||||
limitSent: false,
|
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.capture = capture;
|
||||||
|
let ok: boolean;
|
||||||
|
if (this.wake) {
|
||||||
|
ok = await this.syncMic();
|
||||||
|
} else {
|
||||||
this.micOpen = true;
|
this.micOpen = true;
|
||||||
const ok = await this.device.startMic();
|
ok = await this.device.startMic();
|
||||||
|
}
|
||||||
if (this.capture !== capture || this.stale(generation)) {
|
if (this.capture !== capture || this.stale(generation)) {
|
||||||
// Cancelled while the microphone was opening. Stop unconditionally unless a newer
|
// 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.
|
// capture now owns the microphone: a stop that turns out to be redundant is harmless.
|
||||||
if (!this.capture || this.capture === capture) {
|
if (!this.capture || this.capture === capture) {
|
||||||
this.capture = null;
|
this.capture = null;
|
||||||
this.micOpen = false;
|
|
||||||
this.stopTicker();
|
this.stopTicker();
|
||||||
|
if (this.wake) {
|
||||||
|
await this.syncMic();
|
||||||
|
} else {
|
||||||
|
this.micOpen = false;
|
||||||
await this.device.stopMic();
|
await this.device.stopMic();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
this.capture = null;
|
this.capture = null;
|
||||||
this.micOpen = false;
|
if (!this.wake) this.micOpen = false;
|
||||||
this.dispatch({ type: 'capture_failed', generation, reason: 'mic_refused' });
|
this.dispatch({ type: 'capture_failed', generation, reason: 'mic_refused' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
capture.lastFrameAt = this.now();
|
capture.lastFrameAt = this.now();
|
||||||
this.dispatch({ type: 'capture_started', generation, at: this.now() });
|
this.dispatch({ type: 'capture_started', generation, at: this.now() });
|
||||||
this.startTicker();
|
this.startTicker();
|
||||||
|
if (capture.complete && !capture.limitSent) {
|
||||||
|
capture.limitSent = true;
|
||||||
|
this.dispatch({ type: 'capture_limit', generation });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private onAudio(pcm: Uint8Array): void {
|
private onAudio(pcm: Uint8Array): void {
|
||||||
const capture = this.capture;
|
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.
|
// 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();
|
capture.lastFrameAt = this.now();
|
||||||
const room = capture.maxBytes - capture.bytes;
|
const room = capture.maxBytes - capture.bytes;
|
||||||
if (room > 0) {
|
if (room > 0) {
|
||||||
@@ -692,6 +992,23 @@ export class Controller {
|
|||||||
this.note('capture', 'capture limit reached');
|
this.note('capture', 'capture limit reached');
|
||||||
this.dispatch({ type: 'capture_limit', generation: capture.generation });
|
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> {
|
private async stopCaptureAndSubmit(generation: number, requestId: string): Promise<void> {
|
||||||
@@ -718,6 +1035,12 @@ export class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async closeMic(): Promise<void> {
|
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;
|
if (!this.micOpen) return;
|
||||||
this.micOpen = false;
|
this.micOpen = false;
|
||||||
this.stopTicker();
|
this.stopTicker();
|
||||||
@@ -1008,6 +1331,7 @@ export class Controller {
|
|||||||
case 'foreground_exit':
|
case 'foreground_exit':
|
||||||
// Also fired when the OS menu opens and closes; nothing is torn down here.
|
// Also fired when the OS menu opens and closes; nothing is torn down here.
|
||||||
this.note('lifecycle', event.type);
|
this.note('lifecycle', event.type);
|
||||||
|
this.afterChange();
|
||||||
return this.render();
|
return this.render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { currentAgent, type AppState } from './reducer.ts';
|
import { currentAgent, menuItems, MODE_LABEL, type AppState } from './reducer.ts';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* HUD geometry. Canvas size and line height are documented by Even
|
* HUD geometry. Canvas size and line height are documented by Even
|
||||||
@@ -41,8 +41,37 @@ function clock(seconds: number): string {
|
|||||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The longest question shown back while the agent works; the rest is on the phone. */
|
||||||
|
const HEARD_MAX = 160;
|
||||||
|
|
||||||
|
/** Shown in the status bar for as long as the microphone is open at rest. */
|
||||||
|
export const MIC_OPEN = '● ';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The names to call, as they are said: the first word of each agent's name. As many as fit
|
||||||
|
* comfortably; the rest are still reachable by swiping.
|
||||||
|
*/
|
||||||
|
function callNames(state: AppState): string {
|
||||||
|
const names: string[] = [];
|
||||||
|
let used = 0;
|
||||||
|
for (const { name } of state.agents) {
|
||||||
|
const word = name.trim().split(/\s+/)[0] ?? name;
|
||||||
|
if (names.length > 0 && used + word.length > 80) return `${names.join(' · ')} …`;
|
||||||
|
names.push(word);
|
||||||
|
used += word.length + 3;
|
||||||
|
}
|
||||||
|
return names.join(' · ');
|
||||||
|
}
|
||||||
|
|
||||||
/** Pure: the complete HUD text for a state at a moment in time. */
|
/** Pure: the complete HUD text for a state at a moment in time. */
|
||||||
export function renderHud(state: AppState, nowMs: number): HudFrame {
|
export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||||
|
const frame = renderFrame(state, nowMs);
|
||||||
|
// The microphone is open and listening for a name: every resting screen says so.
|
||||||
|
const resting = state.phase === 'ready' || state.phase === 'answer' || state.phase === 'error' || state.phase === 'cancelled';
|
||||||
|
return state.wakeListening && resting ? { body: frame.body, status: `${MIC_OPEN}${frame.status}` } : frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderFrame(state: AppState, nowMs: number): HudFrame {
|
||||||
// With more than one agent on offer, every screen of an exchange says who it is with.
|
// With more than one agent on offer, every screen of an exchange says who it is with.
|
||||||
const agent = state.agents.length > 1 ? currentAgent(state) : undefined;
|
const agent = state.agents.length > 1 ? currentAgent(state) : undefined;
|
||||||
switch (state.phase) {
|
switch (state.phase) {
|
||||||
@@ -55,21 +84,34 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
|
|||||||
}
|
}
|
||||||
return { body: 'Hermeven\n\nNot connected.\nOpen Hermeven on your phone to pair.', status: 'Double-tap: exit' };
|
return { body: 'Hermeven\n\nNot connected.\nOpen Hermeven on your phone to pair.', status: 'Double-tap: exit' };
|
||||||
|
|
||||||
case 'ready':
|
case 'menu': {
|
||||||
if (agent) {
|
// Plain ASCII marker: the firmware font silently drops characters it does not have.
|
||||||
return {
|
const lines = menuItems(state).map((mode, i) => `${i === state.menuIndex ? '>' : ' '} ${MODE_LABEL[mode]}`);
|
||||||
body: state.notice ? `${agent.name}\n\n${state.notice}.` : `${agent.name}\n\nReady.`,
|
return { body: `Hermeven\n\n${lines.join('\n')}`, status: lines.length > 1 ? 'Tap: open · Swipe: move · 2×: exit' : 'Tap: open · Double-tap: exit' };
|
||||||
status: 'Tap: ask · Swipe: agent · 2×: exit',
|
}
|
||||||
};
|
|
||||||
|
case 'ready': {
|
||||||
|
// With a menu, double tap goes back to it; without one it leaves the app.
|
||||||
|
const out = state.menu ? 'menu' : 'exit';
|
||||||
|
const status = agent ? `Tap: ask · Swipe: agent · 2×: ${out}` : `Tap: ask · Double-tap: ${out}`;
|
||||||
|
if (state.wakeListening && !state.notice) {
|
||||||
|
return agent
|
||||||
|
? { body: `${agent.name}\n\nListening. Say a name, then your question:\n${callNames(state)}`, status }
|
||||||
|
: { body: 'Hermeven\n\nListening. Say your agent’s name, then your question.', status };
|
||||||
|
}
|
||||||
|
if (agent) return { body: state.notice ? `${agent.name}\n\n${state.notice}.` : `${agent.name}\n\nReady.`, status };
|
||||||
|
return { body: state.notice ? `Hermeven\n\n${state.notice}.` : 'Hermeven\n\nReady.', status };
|
||||||
}
|
}
|
||||||
return {
|
|
||||||
body: state.notice ? `Hermeven\n\n${state.notice}.` : 'Hermeven\n\nReady.',
|
|
||||||
status: 'Tap: ask · Double-tap: exit',
|
|
||||||
};
|
|
||||||
|
|
||||||
case 'listening': {
|
case 'listening': {
|
||||||
const elapsed = state.captureStartedAt === null ? 0 : (nowMs - state.captureStartedAt) / 1000;
|
const elapsed = state.captureStartedAt === null ? 0 : (nowMs - state.captureStartedAt) / 1000;
|
||||||
const cap = state.captureMaxSeconds;
|
const cap = state.captureMaxSeconds;
|
||||||
|
if (state.captureAuto) {
|
||||||
|
return {
|
||||||
|
body: `${agent ? `${agent.name} is listening…` : 'Listening…'}\n\nAsk your question. It is sent when you stop speaking.`,
|
||||||
|
status: `● REC ${clock(elapsed)} / ${clock(cap)} · Tap: send · 2×: cancel`,
|
||||||
|
};
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
body: `${agent ? `${agent.name} is listening…` : 'Listening…'}\n\nRecording stops by itself after ${cap} seconds.`,
|
body: `${agent ? `${agent.name} is listening…` : 'Listening…'}\n\nRecording stops by itself after ${cap} seconds.`,
|
||||||
status: `● REC ${clock(elapsed)} / ${clock(cap)} · Tap or release: send · 2×: cancel`,
|
status: `● REC ${clock(elapsed)} / ${clock(cap)} · Tap or release: send · 2×: cancel`,
|
||||||
@@ -79,8 +121,14 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
|
|||||||
case 'transcribing':
|
case 'transcribing':
|
||||||
return { body: 'Transcribing…', status: 'Double-tap: cancel' };
|
return { body: 'Transcribing…', status: 'Double-tap: cancel' };
|
||||||
|
|
||||||
case 'thinking':
|
case 'thinking': {
|
||||||
return { body: agent ? `${agent.name} is thinking…` : 'Thinking…', status: 'Double-tap: cancel' };
|
const title = agent ? `${agent.name} is thinking…` : 'Thinking…';
|
||||||
|
if (!state.heard) return { body: title, status: 'Double-tap: cancel' };
|
||||||
|
// Asked by voice with nothing pressed: show what was understood, so a mishearing is seen
|
||||||
|
// while it can still be cancelled.
|
||||||
|
const heard = state.heard.length > HEARD_MAX ? `${state.heard.slice(0, HEARD_MAX - 1).trimEnd()}…` : state.heard;
|
||||||
|
return { body: `${title}\n\nHeard: ${heard}`, status: 'Double-tap: cancel' };
|
||||||
|
}
|
||||||
|
|
||||||
case 'approval':
|
case 'approval':
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import type { TurnResult } from '@hermeven/contracts';
|
|||||||
*/
|
*/
|
||||||
export type Phase =
|
export type Phase =
|
||||||
| 'unpaired'
|
| 'unpaired'
|
||||||
|
/** The opening menu: choose a mode. Nothing records and nothing is in flight. */
|
||||||
|
| 'menu'
|
||||||
| 'ready'
|
| 'ready'
|
||||||
| 'listening'
|
| 'listening'
|
||||||
| 'transcribing'
|
| 'transcribing'
|
||||||
@@ -35,8 +37,24 @@ export interface Agent {
|
|||||||
name: string;
|
name: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How the app is being used. Both modes talk to the same agents through the same path; the
|
||||||
|
* only difference is whether the microphone listens for a name while at rest.
|
||||||
|
* - agents: the microphone opens on a tap, and the app leaves the glasses when idle.
|
||||||
|
* - handsfree: the microphone is open at rest, and the app stays until closed.
|
||||||
|
*/
|
||||||
|
export type Mode = 'agents' | 'handsfree';
|
||||||
|
|
||||||
|
export const MODE_LABEL: Record<Mode, string> = { handsfree: 'Hands free', agents: 'Agents' };
|
||||||
|
|
||||||
export interface AppState {
|
export interface AppState {
|
||||||
phase: Phase;
|
phase: Phase;
|
||||||
|
/** The app opens on a menu, and double tap at Ready goes back to it (instead of exiting). */
|
||||||
|
menu: boolean;
|
||||||
|
menuIndex: number;
|
||||||
|
mode: Mode;
|
||||||
|
/** Hands free can be offered: this build has it, and nothing has said the bridge cannot do it. */
|
||||||
|
handsFree: boolean;
|
||||||
/**
|
/**
|
||||||
* The agents the bridge offers, default first. Empty when there is only one (or the bridge
|
* The agents the bridge offers, default first. Empty when there is only one (or the bridge
|
||||||
* predates agent selection): nothing about agents is then shown or sent.
|
* predates agent selection): nothing about agents is then shown or sent.
|
||||||
@@ -58,6 +76,15 @@ export interface AppState {
|
|||||||
requestId: string | null;
|
requestId: string | null;
|
||||||
captureStartedAt: number | null;
|
captureStartedAt: number | null;
|
||||||
captureMaxSeconds: number;
|
captureMaxSeconds: number;
|
||||||
|
/** The recording was started by saying an agent's name: it sends itself when the speaker stops. */
|
||||||
|
captureAuto: boolean;
|
||||||
|
/**
|
||||||
|
* The microphone is open at rest, listening for an agent's name. Reported by the controller
|
||||||
|
* from what the microphone actually did, so the HUD's indicator is never a guess.
|
||||||
|
*/
|
||||||
|
wakeListening: boolean;
|
||||||
|
/** The question as it was heard, when it was spoken after a name. Shown while the agent works. */
|
||||||
|
heard: string | null;
|
||||||
pages: string[];
|
pages: string[];
|
||||||
pageIndex: number;
|
pageIndex: number;
|
||||||
/** The answer is a partial one (agent stopped short). Shown on the HUD. */
|
/** The answer is a partial one (agent stopped short). Shown on the HUD. */
|
||||||
@@ -77,6 +104,10 @@ export interface AppState {
|
|||||||
|
|
||||||
export const initialState: AppState = {
|
export const initialState: AppState = {
|
||||||
phase: 'unpaired',
|
phase: 'unpaired',
|
||||||
|
menu: false,
|
||||||
|
menuIndex: 0,
|
||||||
|
mode: 'agents',
|
||||||
|
handsFree: false,
|
||||||
agents: [],
|
agents: [],
|
||||||
agentId: null,
|
agentId: null,
|
||||||
generation: 0,
|
generation: 0,
|
||||||
@@ -86,6 +117,9 @@ export const initialState: AppState = {
|
|||||||
requestId: null,
|
requestId: null,
|
||||||
captureStartedAt: null,
|
captureStartedAt: null,
|
||||||
captureMaxSeconds: 30,
|
captureMaxSeconds: 30,
|
||||||
|
captureAuto: false,
|
||||||
|
wakeListening: false,
|
||||||
|
heard: null,
|
||||||
pages: [],
|
pages: [],
|
||||||
pageIndex: 0,
|
pageIndex: 0,
|
||||||
partial: false,
|
partial: false,
|
||||||
@@ -106,7 +140,12 @@ export type AppEvent =
|
|||||||
storageFault?: boolean;
|
storageFault?: boolean;
|
||||||
agents?: Agent[];
|
agents?: Agent[];
|
||||||
agentId?: string | null;
|
agentId?: string | null;
|
||||||
|
/** Open on the menu. Without it the app opens at Ready, hands free if that is available. */
|
||||||
|
menu?: boolean;
|
||||||
|
handsFree?: boolean;
|
||||||
}
|
}
|
||||||
|
/** Hands free turned out not to be possible (the bridge cannot do it): fall back to Agents. */
|
||||||
|
| { type: 'handsfree_lost' }
|
||||||
/** The user picked another agent (a swipe at Ready). `conversationId` is that agent's own, if it has one. */
|
/** The user picked another agent (a swipe at Ready). `conversationId` is that agent's own, if it has one. */
|
||||||
| { type: 'agent_selected'; agentId: string; conversationId: string | null }
|
| { type: 'agent_selected'; agentId: string; conversationId: string | null }
|
||||||
/**
|
/**
|
||||||
@@ -116,6 +155,16 @@ export type AppEvent =
|
|||||||
*/
|
*/
|
||||||
| { type: 'agent_reconciled'; agentId: string; conversationId: string | null }
|
| { type: 'agent_reconciled'; agentId: string; conversationId: string | null }
|
||||||
| { type: 'unpaired' }
|
| { type: 'unpaired' }
|
||||||
|
/**
|
||||||
|
* An agent was addressed by name and the question followed in the same breath ("Wendy, what
|
||||||
|
* time is it"). `agentId` and `conversationId` are that agent's; null agent = no choice offered.
|
||||||
|
*/
|
||||||
|
| { type: 'wake_text'; freshId: string; agentId: string | null; conversationId: string | null; text: string }
|
||||||
|
/** Only the name was said: record what follows and send it when the speaker stops. */
|
||||||
|
| { type: 'wake_listen'; freshId: string; agentId: string | null; conversationId: string | null }
|
||||||
|
/** A recording started by name heard nothing: back to rest, nothing sent. */
|
||||||
|
| { type: 'capture_abandoned'; generation: number }
|
||||||
|
| { type: 'wake_status'; listening: boolean }
|
||||||
/** Semantic actions. `freshId` is a new UUID supplied by the caller in case a turn starts. */
|
/** Semantic actions. `freshId` is a new UUID supplied by the caller in case a turn starts. */
|
||||||
| { type: 'activate'; freshId: string }
|
| { type: 'activate'; freshId: string }
|
||||||
| { type: 'back' }
|
| { type: 'back' }
|
||||||
@@ -140,7 +189,7 @@ export type AppEvent =
|
|||||||
| { type: 'app_exit' };
|
| { type: 'app_exit' };
|
||||||
|
|
||||||
export type Effect =
|
export type Effect =
|
||||||
| { type: 'start_capture'; generation: number }
|
| { type: 'start_capture'; generation: number; auto?: boolean }
|
||||||
| { type: 'stop_capture_and_submit'; generation: number; requestId: string }
|
| { type: 'stop_capture_and_submit'; generation: number; requestId: string }
|
||||||
| { type: 'discard_capture' }
|
| { type: 'discard_capture' }
|
||||||
| { type: 'submit_text'; generation: number; requestId: string; text: string }
|
| { type: 'submit_text'; generation: number; requestId: string; text: string }
|
||||||
@@ -158,6 +207,11 @@ export interface Step {
|
|||||||
const IDLE: ReadonlySet<Phase> = new Set(['ready', 'answer', 'error', 'cancelled']);
|
const IDLE: ReadonlySet<Phase> = new Set(['ready', 'answer', 'error', 'cancelled']);
|
||||||
const IN_FLIGHT: ReadonlySet<Phase> = new Set(['transcribing', 'thinking', 'approval']);
|
const IN_FLIGHT: ReadonlySet<Phase> = new Set(['transcribing', 'thinking', 'approval']);
|
||||||
|
|
||||||
|
/** The menu's entries, in order. Hands free comes first whenever it can be offered. */
|
||||||
|
export function menuItems(state: Pick<AppState, 'handsFree'>): Mode[] {
|
||||||
|
return state.handsFree ? ['handsfree', 'agents'] : ['agents'];
|
||||||
|
}
|
||||||
|
|
||||||
/** The agent questions go to now, or undefined when the bridge offers no choice. */
|
/** The agent questions go to now, or undefined when the bridge offers no choice. */
|
||||||
export function currentAgent(state: AppState): Agent | undefined {
|
export function currentAgent(state: AppState): Agent | undefined {
|
||||||
if (state.agents.length === 0) return undefined;
|
if (state.agents.length === 0) return undefined;
|
||||||
@@ -169,6 +223,8 @@ function clearTurn(state: AppState): AppState {
|
|||||||
...state,
|
...state,
|
||||||
requestId: null,
|
requestId: null,
|
||||||
captureStartedAt: null,
|
captureStartedAt: null,
|
||||||
|
captureAuto: false,
|
||||||
|
heard: null,
|
||||||
pages: [],
|
pages: [],
|
||||||
pageIndex: 0,
|
pageIndex: 0,
|
||||||
partial: false,
|
partial: false,
|
||||||
@@ -183,6 +239,24 @@ function same(state: AppState): Step {
|
|||||||
return { state, effects: [] };
|
return { state, effects: [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turn to the agent that was addressed by name, with its own conversation. Null when that
|
||||||
|
* agent is not one on offer. A change of agent or conversation starts a new conversation epoch,
|
||||||
|
* so a conversation still being created for the previous one cannot land here.
|
||||||
|
*/
|
||||||
|
function address(state: AppState, agentId: string | null, conversationId: string | null): AppState | null {
|
||||||
|
if (state.agents.length > 0 && agentId !== null && !state.agents.some((a) => a.id === agentId)) return null;
|
||||||
|
const sameAgent = state.agents.length === 0 || agentId === null || agentId === currentAgent(state)?.id;
|
||||||
|
if (sameAgent && conversationId === state.conversationId) return state;
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
agentId: sameAgent ? state.agentId : agentId,
|
||||||
|
conversationId,
|
||||||
|
conversationEpoch: state.conversationEpoch + 1,
|
||||||
|
creatingConversation: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/** Abandon whatever is in progress. The generation bump is what silences late results. */
|
/** Abandon whatever is in progress. The generation bump is what silences late results. */
|
||||||
function abandon(state: AppState): Step {
|
function abandon(state: AppState): Step {
|
||||||
const effects: Effect[] = [];
|
const effects: Effect[] = [];
|
||||||
@@ -209,6 +283,10 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
|||||||
storageFault: event.storageFault === true,
|
storageFault: event.storageFault === true,
|
||||||
agents: event.agents ?? [],
|
agents: event.agents ?? [],
|
||||||
agentId: event.agentId ?? null,
|
agentId: event.agentId ?? null,
|
||||||
|
menu: event.menu === true,
|
||||||
|
handsFree: event.handsFree === true,
|
||||||
|
// With a menu, hands free is something the user chooses. Without one it is simply on.
|
||||||
|
mode: event.menu !== true && event.handsFree === true ? 'handsfree' : 'agents',
|
||||||
};
|
};
|
||||||
if (!event.paired) return same({ ...base, phase: 'unpaired' });
|
if (!event.paired) return same({ ...base, phase: 'unpaired' });
|
||||||
if (event.resumeRequestId) {
|
if (event.resumeRequestId) {
|
||||||
@@ -219,7 +297,20 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
|||||||
effects: [{ type: 'poll', generation: base.generation, requestId: event.resumeRequestId }],
|
effects: [{ type: 'poll', generation: base.generation, requestId: event.resumeRequestId }],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return same({ ...base, phase: 'ready' });
|
return same({ ...base, phase: base.menu ? 'menu' : 'ready' });
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'handsfree_lost': {
|
||||||
|
if (!state.handsFree) return same(state);
|
||||||
|
const wasOn = state.mode === 'handsfree';
|
||||||
|
return same({
|
||||||
|
...state,
|
||||||
|
handsFree: false,
|
||||||
|
mode: 'agents',
|
||||||
|
menuIndex: 0,
|
||||||
|
wakeListening: false,
|
||||||
|
notice: wasOn && state.phase === 'ready' ? 'Hands free is not available' : state.notice,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'agent_selected': {
|
case 'agent_selected': {
|
||||||
@@ -264,7 +355,44 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case 'wake_text': {
|
||||||
|
if (!IDLE.has(state.phase)) return same(state);
|
||||||
|
const addressed = address(state, event.agentId, event.conversationId);
|
||||||
|
if (!addressed) return same(state);
|
||||||
|
const generation = state.generation + 1;
|
||||||
|
return {
|
||||||
|
state: { ...clearTurn(addressed), phase: 'thinking', generation, requestId: event.freshId, heard: event.text },
|
||||||
|
effects: [{ type: 'submit_text', generation, requestId: event.freshId, text: event.text }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'wake_listen': {
|
||||||
|
if (!IDLE.has(state.phase)) return same(state);
|
||||||
|
const addressed = address(state, event.agentId, event.conversationId);
|
||||||
|
if (!addressed) return same(state);
|
||||||
|
const generation = state.generation + 1;
|
||||||
|
return {
|
||||||
|
state: { ...clearTurn(addressed), phase: 'listening', generation, requestId: event.freshId, captureAuto: true },
|
||||||
|
effects: [{ type: 'start_capture', generation, auto: true }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'capture_abandoned': {
|
||||||
|
if (event.generation !== state.generation || state.phase !== 'listening') return same(state);
|
||||||
|
return {
|
||||||
|
state: { ...clearTurn(state), phase: 'ready', generation: state.generation + 1 },
|
||||||
|
effects: [{ type: 'discard_capture' }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'wake_status':
|
||||||
|
return same(event.listening === state.wakeListening ? state : { ...state, wakeListening: event.listening });
|
||||||
|
|
||||||
case 'activate': {
|
case 'activate': {
|
||||||
|
if (state.phase === 'menu') {
|
||||||
|
const mode = menuItems(state)[state.menuIndex] ?? 'agents';
|
||||||
|
return same({ ...clearTurn(state), phase: 'ready', mode, generation: state.generation + 1 });
|
||||||
|
}
|
||||||
if (IDLE.has(state.phase)) {
|
if (IDLE.has(state.phase)) {
|
||||||
const generation = state.generation + 1;
|
const generation = state.generation + 1;
|
||||||
return {
|
return {
|
||||||
@@ -297,7 +425,8 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case 'submit_text': {
|
case 'submit_text': {
|
||||||
if (!IDLE.has(state.phase)) return same(state);
|
// Typed on the phone. Also accepted on the menu: it does not need a mode.
|
||||||
|
if (!IDLE.has(state.phase) && state.phase !== 'menu') return same(state);
|
||||||
const generation = state.generation + 1;
|
const generation = state.generation + 1;
|
||||||
return {
|
return {
|
||||||
state: { ...clearTurn(state), phase: 'thinking', generation, requestId: event.freshId },
|
state: { ...clearTurn(state), phase: 'thinking', generation, requestId: event.freshId },
|
||||||
@@ -306,7 +435,11 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case 'back': {
|
case 'back': {
|
||||||
if (state.phase === 'ready' || state.phase === 'unpaired') return { state, effects: [{ type: 'exit_dialog' }] };
|
if (state.phase === 'ready' && state.menu) {
|
||||||
|
// Leaving a mode. Hands free ends here: the microphone closes with it.
|
||||||
|
return same({ ...clearTurn(state), phase: 'menu', mode: 'agents', menuIndex: 0, generation: state.generation + 1 });
|
||||||
|
}
|
||||||
|
if (state.phase === 'ready' || state.phase === 'unpaired' || state.phase === 'menu') return { state, effects: [{ type: 'exit_dialog' }] };
|
||||||
if (state.phase === 'listening' || IN_FLIGHT.has(state.phase) || state.phase === 'disconnected') return abandon(state);
|
if (state.phase === 'listening' || IN_FLIGHT.has(state.phase) || state.phase === 'disconnected') return abandon(state);
|
||||||
// answer / error / cancelled: step back to the root page.
|
// answer / error / cancelled: step back to the root page.
|
||||||
return same({ ...clearTurn(state), phase: 'ready' });
|
return same({ ...clearTurn(state), phase: 'ready' });
|
||||||
@@ -319,8 +452,12 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
|||||||
|
|
||||||
case 'next_page':
|
case 'next_page':
|
||||||
case 'prev_page': {
|
case 'prev_page': {
|
||||||
if (state.phase !== 'answer') return same(state);
|
|
||||||
const delta = event.type === 'next_page' ? 1 : -1;
|
const delta = event.type === 'next_page' ? 1 : -1;
|
||||||
|
if (state.phase === 'menu') {
|
||||||
|
const menuIndex = Math.min(menuItems(state).length - 1, Math.max(0, state.menuIndex + delta));
|
||||||
|
return same(menuIndex === state.menuIndex ? state : { ...state, menuIndex });
|
||||||
|
}
|
||||||
|
if (state.phase !== 'answer') return same(state);
|
||||||
const pageIndex = Math.min(state.pages.length - 1, Math.max(0, state.pageIndex + delta));
|
const pageIndex = Math.min(state.pages.length - 1, Math.max(0, state.pageIndex + delta));
|
||||||
return same(pageIndex === state.pageIndex ? state : { ...state, pageIndex });
|
return same(pageIndex === state.pageIndex ? state : { ...state, pageIndex });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
/**
|
||||||
|
* Finds stretches of speech in a continuous microphone stream, by loudness alone.
|
||||||
|
*
|
||||||
|
* Pure: no clock (time is counted in samples), no I/O. It is not a speech recogniser and does
|
||||||
|
* not know words; it only decides "someone started talking" and "they stopped", so that the
|
||||||
|
* app can send one utterance at a time instead of a never-ending stream.
|
||||||
|
*
|
||||||
|
* Audio is 16 kHz signed 16-bit little-endian mono (the only format the app handles). It is
|
||||||
|
* examined in 20 ms windows. A window is "voiced" when its level is clearly above the
|
||||||
|
* background, which is tracked continuously while nobody is speaking.
|
||||||
|
*
|
||||||
|
* NOT device-tested: the thresholds are first guesses for a microphone whose levels have not
|
||||||
|
* been measured (see docs/device-test-plan.md).
|
||||||
|
*/
|
||||||
|
export interface SegmenterOptions {
|
||||||
|
/** A pause this long ends the utterance. */
|
||||||
|
endSilenceMs: number;
|
||||||
|
/** Less voiced sound than this in total is a click or a cough, not an utterance. */
|
||||||
|
minSpeechMs: number;
|
||||||
|
/** Audio kept from just before speech was detected, so the first syllable is not clipped. */
|
||||||
|
prerollMs: number;
|
||||||
|
/** An utterance is cut off (and still delivered) at this length. */
|
||||||
|
maxMs: number;
|
||||||
|
/** A window is never voiced below this RMS level (full scale is 32768). */
|
||||||
|
minRms: number;
|
||||||
|
/** A window is voiced when its level is at least this many times the background level. */
|
||||||
|
ratio: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const WAKE_SEGMENTER: SegmenterOptions = {
|
||||||
|
endSilenceMs: 700,
|
||||||
|
minSpeechMs: 240,
|
||||||
|
prerollMs: 400,
|
||||||
|
maxMs: 30_000,
|
||||||
|
minRms: 260,
|
||||||
|
ratio: 3,
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SegmentEvent =
|
||||||
|
| { type: 'start' }
|
||||||
|
/** The utterance, from the preroll to the end of the closing pause. */
|
||||||
|
| { type: 'end'; pcm: Uint8Array }
|
||||||
|
/** What looked like speech was too short to be an utterance. */
|
||||||
|
| { type: 'discard' };
|
||||||
|
|
||||||
|
const WINDOW_BYTES = 640; // 20 ms
|
||||||
|
const WINDOW_MS = 20;
|
||||||
|
/** This many voiced windows in a row start an utterance. */
|
||||||
|
const ONSET_WINDOWS = 3;
|
||||||
|
|
||||||
|
export class SpeechSegmenter {
|
||||||
|
private options: SegmenterOptions;
|
||||||
|
/** Bytes that do not yet fill a window. */
|
||||||
|
private carry = new Uint8Array(0);
|
||||||
|
/** Recent windows while nobody is speaking: the preroll. */
|
||||||
|
private recent: Uint8Array[] = [];
|
||||||
|
/** Windows of the utterance in progress. */
|
||||||
|
private speech: Uint8Array[] | null = null;
|
||||||
|
private voicedRun = 0;
|
||||||
|
private voicedWindows = 0;
|
||||||
|
private silentRun = 0;
|
||||||
|
private levelSum = 0;
|
||||||
|
/** Background level, learned while nobody is speaking. */
|
||||||
|
private floor = 0;
|
||||||
|
|
||||||
|
constructor(options: SegmenterOptions = WAKE_SEGMENTER) {
|
||||||
|
this.options = options;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Someone is talking right now (an utterance has started and not yet ended). */
|
||||||
|
get speaking(): boolean {
|
||||||
|
return this.speech !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Change the timing rules from the next window on, without losing what has been heard. */
|
||||||
|
configure(options: SegmenterOptions): void {
|
||||||
|
this.options = options;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Forget everything heard so far, keeping what was learned about the background level. */
|
||||||
|
reset(): void {
|
||||||
|
this.carry = new Uint8Array(0);
|
||||||
|
this.recent = [];
|
||||||
|
this.speech = null;
|
||||||
|
this.voicedRun = 0;
|
||||||
|
this.voicedWindows = 0;
|
||||||
|
this.silentRun = 0;
|
||||||
|
this.levelSum = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Everything currently held: the utterance in progress, or else the preroll. Used when a
|
||||||
|
* recording takes over from listening, so that what was already being said is not lost.
|
||||||
|
*/
|
||||||
|
buffered(): Uint8Array {
|
||||||
|
return concat(this.speech ?? this.recent);
|
||||||
|
}
|
||||||
|
|
||||||
|
push(pcm: Uint8Array): SegmentEvent[] {
|
||||||
|
const events: SegmentEvent[] = [];
|
||||||
|
let data = pcm;
|
||||||
|
if (this.carry.length) {
|
||||||
|
data = new Uint8Array(this.carry.length + pcm.length);
|
||||||
|
data.set(this.carry);
|
||||||
|
data.set(pcm, this.carry.length);
|
||||||
|
}
|
||||||
|
let offset = 0;
|
||||||
|
for (; offset + WINDOW_BYTES <= data.length; offset += WINDOW_BYTES) {
|
||||||
|
this.window(data.slice(offset, offset + WINDOW_BYTES), events);
|
||||||
|
}
|
||||||
|
this.carry = data.slice(offset);
|
||||||
|
return events;
|
||||||
|
}
|
||||||
|
|
||||||
|
private window(win: Uint8Array, events: SegmentEvent[]): void {
|
||||||
|
const level = rms(win);
|
||||||
|
const voiced = level >= Math.max(this.options.minRms, this.floor * this.options.ratio);
|
||||||
|
|
||||||
|
if (!this.speech) {
|
||||||
|
this.recent.push(win);
|
||||||
|
const keep = Math.max(ONSET_WINDOWS, Math.ceil(this.options.prerollMs / WINDOW_MS));
|
||||||
|
if (this.recent.length > keep) this.recent.shift();
|
||||||
|
if (!voiced) {
|
||||||
|
this.voicedRun = 0;
|
||||||
|
// Follows a quieter room at once and a louder one slowly.
|
||||||
|
this.floor = this.floor === 0 || level < this.floor ? level : this.floor * 0.98 + level * 0.02;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.voicedRun += 1;
|
||||||
|
if (this.voicedRun < ONSET_WINDOWS) return;
|
||||||
|
this.speech = this.recent;
|
||||||
|
this.recent = [];
|
||||||
|
this.voicedWindows = this.voicedRun;
|
||||||
|
this.voicedRun = 0;
|
||||||
|
this.silentRun = 0;
|
||||||
|
this.levelSum = 0;
|
||||||
|
events.push({ type: 'start' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.speech.push(win);
|
||||||
|
this.levelSum += level;
|
||||||
|
if (voiced) {
|
||||||
|
this.voicedWindows += 1;
|
||||||
|
this.silentRun = 0;
|
||||||
|
} else {
|
||||||
|
this.silentRun += 1;
|
||||||
|
}
|
||||||
|
const paused = this.silentRun * WINDOW_MS >= this.options.endSilenceMs;
|
||||||
|
const tooLong = this.speech.length * WINDOW_MS >= this.options.maxMs;
|
||||||
|
if (!paused && !tooLong) return;
|
||||||
|
|
||||||
|
const speech = this.speech;
|
||||||
|
const enough = this.voicedWindows * WINDOW_MS >= this.options.minSpeechMs;
|
||||||
|
if (tooLong && !paused) {
|
||||||
|
// Never a pause in all that time: this is a steady noise, not a voice. Treat its level as
|
||||||
|
// the new background so the next thing delivered is something that stands out from it.
|
||||||
|
this.floor = this.levelSum / speech.length;
|
||||||
|
}
|
||||||
|
this.speech = null;
|
||||||
|
this.voicedWindows = 0;
|
||||||
|
this.silentRun = 0;
|
||||||
|
events.push(enough ? { type: 'end', pcm: concat(speech) } : { type: 'discard' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function rms(win: Uint8Array): number {
|
||||||
|
let sum = 0;
|
||||||
|
const samples = win.length >> 1;
|
||||||
|
for (let i = 0; i < samples; i++) {
|
||||||
|
let v = win[2 * i]! | (win[2 * i + 1]! << 8);
|
||||||
|
if (v & 0x8000) v -= 0x10000;
|
||||||
|
sum += v * v;
|
||||||
|
}
|
||||||
|
return Math.sqrt(sum / samples);
|
||||||
|
}
|
||||||
|
|
||||||
|
function concat(chunks: Uint8Array[]): Uint8Array {
|
||||||
|
let total = 0;
|
||||||
|
for (const chunk of chunks) total += chunk.length;
|
||||||
|
const out = new Uint8Array(total);
|
||||||
|
let offset = 0;
|
||||||
|
for (const chunk of chunks) {
|
||||||
|
out.set(chunk, offset);
|
||||||
|
offset += chunk.length;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -21,6 +21,10 @@ const { controller } = await boot(document, window, {
|
|||||||
// Development only, for automated simulator runs: `?idleExit=off` keeps the app open and
|
// Development only, for automated simulator runs: `?idleExit=off` keeps the app open and
|
||||||
// `?idleExit=fast` shortens the waits. Production builds always use the defaults.
|
// `?idleExit=fast` shortens the waits. Production builds always use the defaults.
|
||||||
idleExit: devIdleExit(),
|
idleExit: devIdleExit(),
|
||||||
|
// Development only, for automated simulator runs: `?wake=off` removes hands-free mode and
|
||||||
|
// `?menu=off` opens at Ready instead of on the menu.
|
||||||
|
wake: !(import.meta.env.DEV && new URLSearchParams(location.search).get('wake') === 'off'),
|
||||||
|
menu: !(import.meta.env.DEV && new URLSearchParams(location.search).get('menu') === 'off'),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Development-only convenience for automated simulator runs, where nothing can type into the
|
// Development-only convenience for automated simulator runs, where nothing can type into the
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
RevokeResponse,
|
RevokeResponse,
|
||||||
SCHEMA_VERSION,
|
SCHEMA_VERSION,
|
||||||
TurnResult,
|
TurnResult,
|
||||||
|
WakeResponse,
|
||||||
type ErrorBody,
|
type ErrorBody,
|
||||||
} from '@hermeven/contracts';
|
} from '@hermeven/contracts';
|
||||||
import type { TSchema } from '@sinclair/typebox';
|
import type { TSchema } from '@sinclair/typebox';
|
||||||
@@ -175,6 +176,21 @@ export class BridgeClient {
|
|||||||
return this.call(TurnResult, 'POST', `/v1/turns?${query}`, { binary: args.pcm }) as Promise<TurnResult>;
|
return this.call(TurnResult, 'POST', `/v1/turns?${query}`, { binary: args.pcm }) as Promise<TurnResult>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One stretch of speech heard while listening: did it begin with an agent's name? Creates
|
||||||
|
* nothing on the bridge. A bridge without wake names answers `not_found`.
|
||||||
|
*/
|
||||||
|
wake(args: { locale: string; pcm: Uint8Array }): Promise<WakeResponse> {
|
||||||
|
const query = new URLSearchParams({
|
||||||
|
schema_version: String(SCHEMA_VERSION),
|
||||||
|
locale: args.locale,
|
||||||
|
encoding: AUDIO_FORMAT.encoding,
|
||||||
|
sample_rate: String(AUDIO_FORMAT.sampleRate),
|
||||||
|
channels: String(AUDIO_FORMAT.channels),
|
||||||
|
});
|
||||||
|
return this.call(WakeResponse, 'POST', `/v1/wake?${query}`, { binary: args.pcm });
|
||||||
|
}
|
||||||
|
|
||||||
getTurn(requestId: string): Promise<TurnResult> {
|
getTurn(requestId: string): Promise<TurnResult> {
|
||||||
return this.call(TurnResult, 'GET', `/v1/turns/${requestId}`) as Promise<TurnResult>;
|
return this.call(TurnResult, 'GET', `/v1/turns/${requestId}`) as Promise<TurnResult>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ function explain(err: unknown): string {
|
|||||||
|
|
||||||
const PHASE_LABEL: Record<string, string> = {
|
const PHASE_LABEL: Record<string, string> = {
|
||||||
unpaired: 'Not paired',
|
unpaired: 'Not paired',
|
||||||
|
menu: 'Menu (choose a mode on the glasses)',
|
||||||
ready: 'Ready',
|
ready: 'Ready',
|
||||||
listening: 'Listening (microphone open)',
|
listening: 'Listening (microphone open)',
|
||||||
transcribing: 'Transcribing',
|
transcribing: 'Transcribing',
|
||||||
@@ -163,7 +164,12 @@ export function mountPhoneUi(root: HTMLElement, controller: Controller, defaults
|
|||||||
|
|
||||||
phase.textContent = PHASE_LABEL[s.state.phase] ?? s.state.phase;
|
phase.textContent = PHASE_LABEL[s.state.phase] ?? s.state.phase;
|
||||||
captureNote.textContent =
|
captureNote.textContent =
|
||||||
`Recording starts only when you tap the glasses, shows “● REC” for as long as the microphone is open, ` +
|
s.wake.enabled
|
||||||
|
? `Hands free: the glasses’ microphone is open whenever the app is at rest (the status line starts with “●”). ` +
|
||||||
|
`Each stretch of speech goes to your bridge, which keeps it only if it begins with an agent’s name. ` +
|
||||||
|
`Say a name and then your question, or tap to ask. Double tap at Ready goes back to the menu and closes the microphone. ` +
|
||||||
|
(s.wake.listening ? 'Listening now.' : 'Not listening at the moment.')
|
||||||
|
: `Recording starts only when you tap the glasses, shows “● REC” for as long as the microphone is open, ` +
|
||||||
`and stops by itself after ${s.state.captureMaxSeconds} seconds.`;
|
`and stops by itself after ${s.state.captureMaxSeconds} seconds.`;
|
||||||
const inFlight = ['listening', 'transcribing', 'thinking', 'approval', 'disconnected'].includes(s.state.phase);
|
const inFlight = ['listening', 'transcribing', 'thinking', 'approval', 'disconnected'].includes(s.state.phase);
|
||||||
askButton.disabled = inFlight;
|
askButton.disabled = inFlight;
|
||||||
|
|||||||
@@ -151,13 +151,14 @@ describe('plain text', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('HUD frames', () => {
|
describe('HUD frames', () => {
|
||||||
const phases: Phase[] = ['unpaired', 'ready', 'listening', 'transcribing', 'thinking', 'approval', 'answer', 'error', 'disconnected', 'cancelled'];
|
const phases: Phase[] = ['unpaired', 'menu', 'ready', 'listening', 'transcribing', 'thinking', 'approval', 'answer', 'error', 'disconnected', 'cancelled'];
|
||||||
const variants = (phase: Phase): AppState[] => {
|
const variants = (phase: Phase): AppState[] => {
|
||||||
const base: AppState = { ...initialState, phase, captureStartedAt: 0, captureMaxSeconds: 120 };
|
const base: AppState = { ...initialState, phase, captureStartedAt: 0, captureMaxSeconds: 120 };
|
||||||
if (phase === 'answer') {
|
if (phase === 'answer') {
|
||||||
return [
|
return [
|
||||||
{ ...base, pages: ['x'], pageIndex: 0 },
|
{ ...base, pages: ['x'], pageIndex: 0 },
|
||||||
{ ...base, pages: Array(99).fill('x'), pageIndex: 98, partial: true },
|
{ ...base, pages: Array(99).fill('x'), pageIndex: 98, partial: true },
|
||||||
|
{ ...base, pages: Array(99).fill('x'), pageIndex: 98, partial: true, wakeListening: true, agents: [{ id: 'default', name: 'Pepper' }, { id: 'natalie', name: 'Natalie' }], agentId: 'natalie' },
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
if (phase === 'disconnected') {
|
if (phase === 'disconnected') {
|
||||||
@@ -172,9 +173,24 @@ describe('HUD frames', () => {
|
|||||||
return [
|
return [
|
||||||
{ ...base, error: { code: 'outcome_unknown', hud: 'The outcome is unknown. Check the agent before asking again.', retryable: false } },
|
{ ...base, error: { code: 'outcome_unknown', hud: 'The outcome is unknown. Check the agent before asking again.', retryable: false } },
|
||||||
{ ...base, error: { code: 'agent_timeout', hud: 'The agent ran out of time and was stopped. Actions it had already taken are not undone.', retryable: true } },
|
{ ...base, error: { code: 'agent_timeout', hud: 'The agent ran out of time and was stopped. Actions it had already taken are not undone.', retryable: true } },
|
||||||
|
{ ...base, wakeListening: true, error: { code: 'agent_timeout', hud: 'The agent ran out of time and was stopped.', retryable: true } },
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
if (phase === 'ready') return [base, { ...base, notice: 'New conversation' }];
|
// Listening for a name: sixteen agents with the longest names allowed, and none.
|
||||||
|
const many = Array.from({ length: 16 }, (_, i) => ({ id: `a${i}`, name: 'Wwwwwwwwwwwwwwwwwwwwwwww' }));
|
||||||
|
const few = [
|
||||||
|
{ id: 'default', name: 'Pepper' },
|
||||||
|
{ id: 'wendy', name: 'Wendy' },
|
||||||
|
{ id: 'cody', name: 'Cody' },
|
||||||
|
];
|
||||||
|
const wake = { wakeListening: true };
|
||||||
|
if (phase === 'menu') return [base, { ...base, handsFree: true }, { ...base, handsFree: true, menuIndex: 1 }];
|
||||||
|
if (phase === 'ready') {
|
||||||
|
return [{ ...base, menu: true }, { ...base, menu: true, ...wake, agents: few }, base, { ...base, notice: 'New conversation' }, { ...base, ...wake }, { ...base, ...wake, agents: few }, { ...base, ...wake, agents: many }, { ...base, ...wake, agents: few, notice: 'New conversation' }];
|
||||||
|
}
|
||||||
|
if (phase === 'listening') return [base, { ...base, captureAuto: true }, { ...base, captureAuto: true, agents: few }];
|
||||||
|
if (phase === 'thinking') return [base, { ...base, heard: 'W'.repeat(4000) }, { ...base, agents: few, heard: 'What is on my calendar tomorrow?' }];
|
||||||
|
if (phase === 'cancelled') return [base, { ...base, ...wake }];
|
||||||
if (phase === 'unpaired') return [base, { ...base, storageFault: true }];
|
if (phase === 'unpaired') return [base, { ...base, storageFault: true }];
|
||||||
return [base];
|
return [base];
|
||||||
};
|
};
|
||||||
@@ -201,6 +217,20 @@ describe('HUD frames', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('an open microphone at rest is always marked, and never claimed while it is closed', () => {
|
||||||
|
for (const phase of ['ready', 'answer', 'error', 'cancelled'] as Phase[]) {
|
||||||
|
const state: AppState = { ...initialState, phase, pages: ['x'] };
|
||||||
|
expect(renderHud({ ...state, wakeListening: true }, 0).status.startsWith('● ')).toBe(true);
|
||||||
|
expect(renderHud(state, 0).status).not.toContain('●');
|
||||||
|
}
|
||||||
|
// In flight the microphone is closed, whatever the flag last said.
|
||||||
|
for (const phase of ['transcribing', 'thinking', 'approval', 'disconnected', 'unpaired'] as Phase[]) {
|
||||||
|
expect(renderHud({ ...initialState, phase, wakeListening: true }, 0).status).not.toContain('●');
|
||||||
|
}
|
||||||
|
const ready = renderHud({ ...initialState, phase: 'ready', wakeListening: true, agents: [{ id: 'default', name: 'Pepper' }, { id: 'wendy', name: 'Wendy' }] }, 0);
|
||||||
|
expect(ready.body).toBe('Pepper\n\nListening. Say a name, then your question:\nPepper · Wendy');
|
||||||
|
});
|
||||||
|
|
||||||
it('errors offer a recovery action and send detail to the phone', () => {
|
it('errors offer a recovery action and send detail to the phone', () => {
|
||||||
const frame = renderHud({ ...initialState, phase: 'error', error: { code: 'stt_empty', hud: 'No speech was recognised.', retryable: true } }, 0);
|
const frame = renderHud({ ...initialState, phase: 'error', error: { code: 'stt_empty', hud: 'No speech was recognised.', retryable: true } }, 0);
|
||||||
expect(frame.body).toContain('No speech was recognised.');
|
expect(frame.body).toContain('No speech was recognised.');
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { SpeechSegmenter, WAKE_SEGMENTER, type SegmentEvent } from '../src/core/vad.ts';
|
||||||
|
|
||||||
|
/** Synthetic audio: a tone stands in for a voice, low noise for a room. Not speech. */
|
||||||
|
function tone(ms: number, amplitude = 6000): Uint8Array {
|
||||||
|
const samples = (ms * 16000) / 1000;
|
||||||
|
const out = new Uint8Array(samples * 2);
|
||||||
|
for (let i = 0; i < samples; i++) {
|
||||||
|
const v = Math.round(Math.sin((2 * Math.PI * 300 * i) / 16000) * amplitude) & 0xffff;
|
||||||
|
out[2 * i] = v & 0xff;
|
||||||
|
out[2 * i + 1] = v >> 8;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
const room = (ms: number, amplitude = 40) => tone(ms, amplitude);
|
||||||
|
|
||||||
|
function feed(segmenter: SpeechSegmenter, ...clips: Uint8Array[]): SegmentEvent[] {
|
||||||
|
const events: SegmentEvent[] = [];
|
||||||
|
for (const clip of clips) {
|
||||||
|
// In 100 ms frames, as the glasses deliver them.
|
||||||
|
for (let offset = 0; offset < clip.length; offset += 3200) events.push(...segmenter.push(clip.subarray(offset, offset + 3200)));
|
||||||
|
}
|
||||||
|
return events;
|
||||||
|
}
|
||||||
|
const ms = (pcm: Uint8Array) => pcm.length / 32;
|
||||||
|
|
||||||
|
describe('speech segmenter', () => {
|
||||||
|
it('silence and steady room noise produce nothing', () => {
|
||||||
|
const segmenter = new SpeechSegmenter();
|
||||||
|
expect(feed(segmenter, new Uint8Array(32000 * 5), room(5000))).toEqual([]);
|
||||||
|
expect(segmenter.speaking).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('delivers one utterance, with its lead-in, once the speaker pauses', () => {
|
||||||
|
const segmenter = new SpeechSegmenter();
|
||||||
|
const events = feed(segmenter, room(1000), tone(1500), room(1000));
|
||||||
|
expect(events.map((e) => e.type)).toEqual(['start', 'end']);
|
||||||
|
const end = events[1] as Extract<SegmentEvent, { type: 'end' }>;
|
||||||
|
// Speech, the preroll before it and the closing pause; not the whole second of lead-in.
|
||||||
|
expect(ms(end.pcm)).toBeGreaterThanOrEqual(1500 + WAKE_SEGMENTER.endSilenceMs);
|
||||||
|
expect(ms(end.pcm)).toBeLessThanOrEqual(1500 + WAKE_SEGMENTER.endSilenceMs + WAKE_SEGMENTER.prerollMs + 60);
|
||||||
|
expect(end.pcm.length % 2).toBe(0);
|
||||||
|
expect(segmenter.speaking).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a short pause inside a sentence does not split it; a long one does', () => {
|
||||||
|
const segmenter = new SpeechSegmenter();
|
||||||
|
const one = feed(segmenter, room(500), tone(600), room(300), tone(600), room(1000));
|
||||||
|
expect(one.map((e) => e.type)).toEqual(['start', 'end']);
|
||||||
|
const two = feed(segmenter, tone(600), room(900), tone(600), room(900));
|
||||||
|
expect(two.map((e) => e.type)).toEqual(['start', 'end', 'start', 'end']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a click is discarded, not delivered', () => {
|
||||||
|
const segmenter = new SpeechSegmenter();
|
||||||
|
expect(feed(segmenter, room(500), tone(100), room(1000)).map((e) => e.type)).toEqual(['start', 'discard']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('frames of any size give the same result', () => {
|
||||||
|
const clip = new Uint8Array([...room(600), ...tone(900), ...room(900)]);
|
||||||
|
const a = new SpeechSegmenter();
|
||||||
|
const b = new SpeechSegmenter();
|
||||||
|
const whole = a.push(clip);
|
||||||
|
const pieces: SegmentEvent[] = [];
|
||||||
|
for (let offset = 0; offset < clip.length; offset += 1001) pieces.push(...b.push(clip.subarray(offset, offset + 1001)));
|
||||||
|
expect(pieces).toEqual(whole);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a noise that never pauses is cut at the limit and then becomes the background', () => {
|
||||||
|
const segmenter = new SpeechSegmenter({ ...WAKE_SEGMENTER, maxMs: 3000 });
|
||||||
|
const events = feed(segmenter, room(500), tone(10_000, 3000));
|
||||||
|
expect(events.filter((e) => e.type === 'end')).toHaveLength(1);
|
||||||
|
// Something clearly louder than that noise is still heard as speech.
|
||||||
|
expect(feed(segmenter, tone(1000, 20_000), tone(1000, 3000)).map((e) => e.type)).toEqual(['start', 'end']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adapts to a louder room: steady noise above the minimum level stops counting as speech', () => {
|
||||||
|
const segmenter = new SpeechSegmenter({ ...WAKE_SEGMENTER, maxMs: 2000 });
|
||||||
|
feed(segmenter, room(4000, 600));
|
||||||
|
expect(feed(segmenter, room(4000, 600))).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hands over what it is holding, and can be retimed without losing it', () => {
|
||||||
|
const segmenter = new SpeechSegmenter();
|
||||||
|
feed(segmenter, room(1000), tone(800));
|
||||||
|
expect(segmenter.speaking).toBe(true);
|
||||||
|
expect(ms(segmenter.buffered())).toBeGreaterThanOrEqual(800);
|
||||||
|
segmenter.configure({ ...WAKE_SEGMENTER, endSilenceMs: 1200 });
|
||||||
|
expect(feed(segmenter, room(1000))).toEqual([]);
|
||||||
|
expect(feed(segmenter, room(300)).map((e) => e.type)).toEqual(['end']);
|
||||||
|
segmenter.reset();
|
||||||
|
expect(segmenter.buffered().length).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -10,6 +10,10 @@ HERMES_PROFILE_LABEL=default
|
|||||||
# HERMEVEN_AGENTS=wendy,cody
|
# HERMEVEN_AGENTS=wendy,cody
|
||||||
# HERMEVEN_AGENT_WENDY_API_KEY=replace-with-wendy-profile-api-server-key
|
# HERMEVEN_AGENT_WENDY_API_KEY=replace-with-wendy-profile-api-server-key
|
||||||
# HERMEVEN_AGENT_CODY_API_KEY=replace-with-cody-profile-api-server-key
|
# HERMEVEN_AGENT_CODY_API_KEY=replace-with-cody-profile-api-server-key
|
||||||
|
# Each agent is called by voice with the first word of its name. If the speech model writes a
|
||||||
|
# name another way (the phone's Diagnostics shows near misses), add those spellings:
|
||||||
|
# HERMEVEN_AGENT_CODY_WAKE=kody,codi
|
||||||
|
# HERMEVEN_AGENT_WAKE=peper
|
||||||
|
|
||||||
HERMEVEN_HOST=127.0.0.1
|
HERMEVEN_HOST=127.0.0.1
|
||||||
HERMEVEN_PORT=8787
|
HERMEVEN_PORT=8787
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ answer text is erased from the bridge 15 minutes after a turn ends (configurable
|
|||||||
network and no randomness: request ids arrive inside events and work leaves as effects.
|
network and no randomness: request ids arrive inside events and work leaves as effects.
|
||||||
|
|
||||||
```
|
```
|
||||||
READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER
|
MENU -> READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER
|
||||||
plus APPROVAL, ERROR, DISCONNECTED, CANCELLED, UNPAIRED
|
plus APPROVAL, ERROR, DISCONNECTED, CANCELLED, UNPAIRED
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -103,4 +103,5 @@ automatically under a new request id.
|
|||||||
- Polling only; no streaming.
|
- Polling only; no streaming.
|
||||||
- A second question while one is running in the same conversation is refused
|
- A second question while one is running in the same conversation is refused
|
||||||
(`conversation_busy`), not queued.
|
(`conversation_busy`), not queued.
|
||||||
- Capture ends by tap or cap. There is no end-of-speech detection.
|
- A tapped capture ends by tap or cap. Only a recording started by an agent's name ends when
|
||||||
|
the speaker stops (`docs/decisions/0004-always-listening.md`).
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ Every error has the shape:
|
|||||||
| `GET /v1/agents` | The agents this device may talk to, default first: `{agents: [{id, name}]}`. Ids and display names only; no address, profile or key. Added after 0.1.x: an older bridge answers 404 `not_found`, which a client must treat as "one agent". | 200 |
|
| `GET /v1/agents` | The agents this device may talk to, default first: `{agents: [{id, name}]}`. Ids and display names only; no address, profile or key. Added after 0.1.x: an older bridge answers 404 `not_found`, which a client must treat as "one agent". | 200 |
|
||||||
| `POST /v1/conversations` | Start a new conversation. Optional `agent_id` (an id from `/v1/agents`; omitted = the default agent; anything else is 400 `invalid_request`). Closes the device's previous conversation **with that agent** only. | 201 |
|
| `POST /v1/conversations` | Start a new conversation. Optional `agent_id` (an id from `/v1/agents`; omitted = the default agent; anything else is 400 `invalid_request`). Closes the device's previous conversation **with that agent** only. | 201 |
|
||||||
| `POST /v1/turns` | Create one turn (text or audio). | 202, or 200 for a duplicate |
|
| `POST /v1/turns` | Create one turn (text or audio). | 202, or 200 for a duplicate |
|
||||||
|
| `POST /v1/wake` | One stretch of speech heard while the app was open (raw audio body, same format as an audio turn; query: `schema_version`, `locale`, `encoding`, `sample_rate`, `channels`). Transcribed in memory and dropped. Answers `{matched, agent_id, text, near_miss}`: whether it **began** with an agent's name, which agent, and what was said after the name (empty for the name alone). When not matched `text` is always empty; `near_miss` is the first word if it was close to a name. Creates no turn and sends nothing to any agent. 404 `not_found` when speech-to-text is off or no agent has a usable name (also what an older bridge answers); 429 `rate_limited` over `HERMEVEN_WAKE_CHECKS_PER_MINUTE` (default 30) or while this device's previous check is still running. A failed transcription is answered as not matched. | 200 |
|
||||||
| `GET /v1/turns/{request_id}` | Current state and result. | 200 |
|
| `GET /v1/turns/{request_id}` | Current state and result. | 200 |
|
||||||
| `POST /v1/turns/{request_id}/cancel` | Request cancellation. Idempotent. | 200 |
|
| `POST /v1/turns/{request_id}/cancel` | Request cancellation. Idempotent. | 200 |
|
||||||
|
|
||||||
@@ -39,8 +40,15 @@ HERMEVEN_AGENTS=wendy,cody # extra agent ids, in display order
|
|||||||
HERMEVEN_AGENT_WENDY_API_KEY=... # required for each extra agent
|
HERMEVEN_AGENT_WENDY_API_KEY=... # required for each extra agent
|
||||||
HERMEVEN_AGENT_WENDY_PROFILE=wendy # optional; default: the id
|
HERMEVEN_AGENT_WENDY_PROFILE=wendy # optional; default: the id
|
||||||
HERMEVEN_AGENT_WENDY_NAME=Wendy # optional; default: the id, capitalised
|
HERMEVEN_AGENT_WENDY_NAME=Wendy # optional; default: the id, capitalised
|
||||||
|
HERMEVEN_AGENT_WENDY_WAKE=wendi,windy # optional; extra spoken forms of the name
|
||||||
|
HERMEVEN_AGENT_WAKE=peper # the same, for the default agent
|
||||||
```
|
```
|
||||||
|
|
||||||
|
An agent is called by voice with the first word of its name ("Cody R." answers to "cody"), plus
|
||||||
|
any aliases. The default agent answers to its name only once `HERMEVEN_AGENT_NAME` is set. Two
|
||||||
|
agents may not answer to the same word. Wake words are never sent to a client. See
|
||||||
|
`docs/decisions/0004-always-listening.md`.
|
||||||
|
|
||||||
The list is the owner's allow-list. A client names an agent only by id, only when creating a
|
The list is the owner's allow-list. A client names an agent only by id, only when creating a
|
||||||
conversation, and the id is checked against the list; it is never used to build an address. A
|
conversation, and the id is checked against the list; it is never used to build an address. A
|
||||||
turn goes to the agent of its conversation. Each agent has its own conversation and its own
|
turn goes to the agent of its conversation. Each agent has its own conversation and its own
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
# 0004: An opening menu, and a hands-free mode that listens for an agent's name
|
||||||
|
|
||||||
|
Status: implemented with fakes only; **nothing here is device-tested**. Date: 2026-11-28.
|
||||||
|
|
||||||
|
Dan (2026-11-28) first asked for the app to be always listening ("I want to be able to say
|
||||||
|
'Wendy' to send whatever follows to Wendy, Cody to Cody"), then, after reading what that costs,
|
||||||
|
chose: leave the app as it is, add this as a "hands free" mode, and open on a menu with
|
||||||
|
"Hands free" first and "Agents" second, so that after "Hey Even, launch Pepper" one tap starts it.
|
||||||
|
|
||||||
|
## The menu
|
||||||
|
|
||||||
|
The app opens on a menu, which is now the root page:
|
||||||
|
|
||||||
|
```
|
||||||
|
Hermeven
|
||||||
|
|
||||||
|
> Hands free
|
||||||
|
Agents
|
||||||
|
```
|
||||||
|
|
||||||
|
Swipe moves, tap opens, double tap asks the system to exit. Double tap at Ready goes back to the
|
||||||
|
menu (it used to exit). An untouched menu leaves the glasses after 30 s, like Ready does. A
|
||||||
|
question that was still running when the app was last closed is shown instead of the menu.
|
||||||
|
|
||||||
|
**Agents** is the app exactly as it was in 0.2.0: tap or hold to ask, swipe to choose, leaves
|
||||||
|
when idle, the microphone opens only on a tap.
|
||||||
|
|
||||||
|
**Hands free** is the same screens, agents, conversations and question path, with one flag set.
|
||||||
|
The flag does two things: the microphone listens while the app is at rest, and the app does not
|
||||||
|
leave by itself. There is no second implementation of agents. The mode is not remembered: every
|
||||||
|
launch starts at the menu with the microphone closed, and going back to the menu closes it.
|
||||||
|
|
||||||
|
Later entries (Telegram, spoken answers through a headset or Android Auto) are not designed
|
||||||
|
here. The menu takes more entries; a mode that needs its own screens will need more than a flag.
|
||||||
|
|
||||||
|
## Hands free
|
||||||
|
|
||||||
|
While in this mode and at rest (Ready, an answer, an error, "Cancelled") the glasses' microphone
|
||||||
|
is open. The status line starts with `●` for exactly as long as it is.
|
||||||
|
|
||||||
|
- "Wendy, what is on my calendar" in one breath: the question goes to Wendy.
|
||||||
|
- "Wendy" alone: a recording starts for Wendy and is sent when the speaker stops (1.2 s pause).
|
||||||
|
If nothing is said for 6 s it is dropped.
|
||||||
|
- The name must be the **first** thing said ("hey"/"ok" before it is allowed). A name in the
|
||||||
|
middle of a sentence does nothing.
|
||||||
|
- Tap, hold-to-talk and swipe-to-choose all still work.
|
||||||
|
- While a question is being transcribed or answered the microphone is closed.
|
||||||
|
- The app does not leave the glasses by itself while in this mode.
|
||||||
|
|
||||||
|
## How
|
||||||
|
|
||||||
|
| Step | Where | Why there |
|
||||||
|
|---|---|---|
|
||||||
|
| Find stretches of speech | Phone, `core/vad.ts`, loudness only | So silence is never uploaded, and one utterance is one request. |
|
||||||
|
| Transcribe and test for a leading name | Bridge, `POST /v1/wake`, the Whisper already there | The SDK gives raw PCM only; a keyword model in the WebView would need training per name. |
|
||||||
|
| Ask the agent | The existing turn path (a text turn, or an audio turn after a name alone) | Request ids, deduplication, cancel and recovery are unchanged. A wake check creates nothing. |
|
||||||
|
|
||||||
|
Matching is exact, against the first word of the agent's display name or an alias from
|
||||||
|
`HERMEVEN_AGENT_<ID>_WAKE`. A word that is only close ("Wendi", "copy") is reported to the phone's
|
||||||
|
Diagnostics as a near miss and is never acted on.
|
||||||
|
|
||||||
|
## What this reverses
|
||||||
|
|
||||||
|
- "The microphone opens only on a tap" and "is never reopened without a new tap"
|
||||||
|
(`docs/feasibility.md` section 2) hold in Agents and not in Hands free.
|
||||||
|
- Idle exit (0.1.1) is suspended in Hands free.
|
||||||
|
- Double tap at Ready no longer opens the system exit dialog; the menu is the root page now.
|
||||||
|
Whether Even's review accepts a root page reached by two double taps is unverified.
|
||||||
|
- "There is no end-of-speech detection" (0003): there is now, for recordings started by name.
|
||||||
|
- The phone's Diagnostics may now show one spoken word (a near miss). Nothing else spoken
|
||||||
|
appears in any log.
|
||||||
|
|
||||||
|
## Owner decisions pending (decide on the device)
|
||||||
|
|
||||||
|
1. In Hands free, staying open means phone notifications may not reach the lenses (one observation, 2026-11-21).
|
||||||
|
2. In Hands free, an agent that can act (Pepper sent a Telegram message) can be started by speech nobody
|
||||||
|
pressed a button for. Mitigations are the first-word rule, exact matching, the "Heard: ..."
|
||||||
|
line while the agent works, and double tap to cancel. There is no confirmation step.
|
||||||
|
3. In Hands free, every stretch of speech near the glasses, addressed to an agent or not, is uploaded to the
|
||||||
|
bridge and transcribed there before being dropped.
|
||||||
|
4. The names are needed on every question, including follow-ups.
|
||||||
|
5. The menu costs one extra tap before the first question in Agents.
|
||||||
|
|
||||||
|
## Unknown until tried on a G2
|
||||||
|
|
||||||
|
Microphone level and background noise against the detector's thresholds (first guesses); whether
|
||||||
|
Whisper spells the names as configured; delay from the end of speech to "thinking" (one upload
|
||||||
|
and one transcription, about 1 to 2 s on the server's figures); battery with the microphone open
|
||||||
|
continuously; whether the stream survives a locked phone for long periods; the server's CPU with
|
||||||
|
a conversation or a television nearby (each stretch of speech is a transcription; capped at 30
|
||||||
|
checks a minute, one at a time).
|
||||||
@@ -77,6 +77,20 @@ If A13 fails, stop and report it. It is a product-level blocker, not a bug to wo
|
|||||||
| C10 | Battery: glasses and phone percentage at start and after a stated duration and number of questions. | The four numbers and the duration. Do not extrapolate. |
|
| C10 | Battery: glasses and phone percentage at start and after a stated duration and number of questions. | The four numbers and the duration. Do not extrapolate. |
|
||||||
| C11 | Per question: seconds from second tap to answer, noted for at least 10 questions. | The raw list. The phone page shows the STT and agent split for each. |
|
| C11 | Per question: seconds from second tap to answer, noted for at least 10 questions. | The raw list. The phone page shows the STT and agent split for each. |
|
||||||
|
|
||||||
|
## D. The menu and hands-free mode (0.3.0; nothing here has been run)
|
||||||
|
|
||||||
|
| # | Do | Record | Answers |
|
||||||
|
|---|---|---|---|
|
||||||
|
| D0 | "Hey Even, launch Pepper". | Does the menu appear with `>` beside "Hands free"? Do swipes move it? Does double tap at Ready come back to it, and double tap on the menu show the exit dialog? | The menu on a real G2; whether `>` and the indent render. |
|
||||||
|
| D1 | Tap "Hands free" and leave it. | Does the status line start with `●`? Does the body list the names? | The microphone opens without a further tap on a real G2. |
|
||||||
|
| D2 | Say "Wendy, what time is it" at a normal volume. Repeat for each agent, five times each. | How many reached the right agent. For misses, the "heard ..." line in Diagnostics, if any. | Detector thresholds; how Whisper spells each name (aliases to add). |
|
||||||
|
| D3 | Say only a name, wait for "... is listening", ask, stop speaking. | Seconds from the name to the screen changing; whether the question was sent whole. | Name-only flow; the 1.2 s end-of-speech pause. |
|
||||||
|
| D4 | Talk to someone for two minutes without using a name. Then mention an agent mid-sentence. | Did anything start? | False triggers. |
|
||||||
|
| D5 | Same with a television or music on. | Did anything start? Did a real "Wendy, ..." still work? | Noise. |
|
||||||
|
| D6 | Leave it open 30 minutes, phone locked in a pocket, then say "Pepper, are you there". | Did it answer? Battery of glasses and phone before and after. | Whether the stream survives; battery cost. |
|
||||||
|
| D7 | While it is open, have a notification arrive. | Did it reach the lenses? | The cost of staying open. |
|
||||||
|
| D8 | Double tap back to the menu, choose "Agents". | Does `●` go away, does tap still work, does the app leave by itself again? | Leaving hands free. |
|
||||||
|
|
||||||
## Reporting
|
## Reporting
|
||||||
|
|
||||||
Anything that fails in A13, A14, A15 or C1 is a blocker or a stated limitation of the product, to
|
Anything that fails in A13, A14, A15 or C1 is a blocker or a stated limitation of the product, to
|
||||||
|
|||||||
@@ -69,6 +69,18 @@ Stated so they are not mistaken for protections.
|
|||||||
sandboxed process. It no longer stalls the bridge (measured 3 ms), but a crash inside the
|
sandboxed process. It no longer stalls the bridge (measured 3 ms), but a crash inside the
|
||||||
native runtime could still take the bridge down; systemd restarts it and in-flight turns are
|
native runtime could still take the bridge down; systemd restarts it and in-flight turns are
|
||||||
recovered or failed honestly.
|
recovered or failed honestly.
|
||||||
|
3c. **In hands-free mode (0.3.0; chosen on the opening menu at each launch, never on by itself)
|
||||||
|
the microphone is open whenever the app is at rest**, and every stretch of speech near the glasses is uploaded to the bridge
|
||||||
|
and transcribed, whoever is speaking and whether or not it is meant for an agent. The bridge
|
||||||
|
keeps and returns only speech that begins with an agent's name; the rest is dropped after the
|
||||||
|
transcription call and is not logged. That is a promise about this code, not a technical
|
||||||
|
barrier: whoever controls the bridge host could record it. People near the wearer are not
|
||||||
|
told. The HUD marks the open microphone with `●`; nothing outside the lenses does.
|
||||||
|
3d. **In hands-free mode an agent can be started without a button.** Speech that begins with an agent's name is sent
|
||||||
|
to that agent with whatever tools its Hermes profile allows, with no confirmation. A name is
|
||||||
|
matched exactly and only as the first word, and what was heard is shown while the agent
|
||||||
|
works, but a mis-transcription, another person saying the name, or audio from a speaker can
|
||||||
|
all start a turn.
|
||||||
4. **In the simulator, raw audio frames are echoed to the WebView console.** Whether the phone
|
4. **In the simulator, raw audio frames are echoed to the WebView console.** Whether the phone
|
||||||
does the same is unknown and is on the device checklist. If it does, recordings would be
|
does the same is unknown and is on the device checklist. If it does, recordings would be
|
||||||
visible to whoever can read that console.
|
visible to whoever can read that console.
|
||||||
|
|||||||
@@ -200,6 +200,42 @@ export const AudioTurnQuery = Type.Object(
|
|||||||
);
|
);
|
||||||
export type AudioTurnQuery = Static<typeof AudioTurnQuery>;
|
export type AudioTurnQuery = Static<typeof AudioTurnQuery>;
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------- wake
|
||||||
|
/**
|
||||||
|
* Query string of POST /v1/wake. The body is raw audio, as for an audio turn: one stretch of
|
||||||
|
* speech heard while the app was open. The bridge transcribes it and says whether it began
|
||||||
|
* with an agent's name. Nothing is stored and no turn is created.
|
||||||
|
*/
|
||||||
|
export const WakeQuery = Type.Object(
|
||||||
|
{
|
||||||
|
schema_version: Type.Literal(String(SCHEMA_VERSION)),
|
||||||
|
locale: Locale,
|
||||||
|
encoding: Type.Literal(AUDIO_FORMAT.encoding),
|
||||||
|
sample_rate: Type.Literal(String(AUDIO_FORMAT.sampleRate)),
|
||||||
|
channels: Type.Literal(String(AUDIO_FORMAT.channels)),
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
export type WakeQuery = Static<typeof WakeQuery>;
|
||||||
|
|
||||||
|
export const WakeResponse = Type.Object(
|
||||||
|
{
|
||||||
|
schema_version: SchemaVersion,
|
||||||
|
/** The speech began with an agent's name. */
|
||||||
|
matched: Type.Boolean(),
|
||||||
|
agent_id: Type.Union([AgentId, Type.Null()]),
|
||||||
|
/**
|
||||||
|
* What was said after the name, when matched (empty when only the name was said). Always
|
||||||
|
* empty when not matched: speech that was not for an agent is not returned.
|
||||||
|
*/
|
||||||
|
text: Type.String({ maxLength: DEFAULT_LIMITS.textMaxChars }),
|
||||||
|
/** Not matched, but the first word was close to an agent's name: that one word, for tuning aliases. */
|
||||||
|
near_miss: Type.Union([Type.String({ maxLength: 24 }), Type.Null()]),
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
export type WakeResponse = Static<typeof WakeResponse>;
|
||||||
|
|
||||||
export const TURN_STATES = [
|
export const TURN_STATES = [
|
||||||
'accepted',
|
'accepted',
|
||||||
'transcribing',
|
'transcribing',
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from 'node:fs';
|
|||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
import { AUDIO_FORMAT, DEFAULT_LIMITS } from '@hermeven/contracts';
|
import { AUDIO_FORMAT, DEFAULT_LIMITS } from '@hermeven/contracts';
|
||||||
import { validateManifest, type ModelManifest } from './stt/modelStore.mjs';
|
import { validateManifest, type ModelManifest } from './stt/modelStore.mjs';
|
||||||
|
import { wakeWordsFor } from './wake.ts';
|
||||||
|
|
||||||
export interface AgentConfig {
|
export interface AgentConfig {
|
||||||
/** `default` for the main agent; otherwise the id from HERMEVEN_AGENTS. */
|
/** `default` for the main agent; otherwise the id from HERMEVEN_AGENTS. */
|
||||||
@@ -10,6 +11,11 @@ export interface AgentConfig {
|
|||||||
name: string;
|
name: string;
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
apiKey: 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 const DEFAULT_AGENT_ID = 'default';
|
||||||
@@ -65,6 +71,8 @@ export interface BridgeConfig {
|
|||||||
textMaxChars: number;
|
textMaxChars: number;
|
||||||
audioMaxBytes: number;
|
audioMaxBytes: number;
|
||||||
turnsPerMinute: number;
|
turnsPerMinute: number;
|
||||||
|
/** Wake checks (speech heard while the app is open, tested for a leading agent name). */
|
||||||
|
wakeChecksPerMinute: number;
|
||||||
pairingAttemptsPerMinute: number;
|
pairingAttemptsPerMinute: number;
|
||||||
};
|
};
|
||||||
credentials: {
|
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
|
* 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>_API_KEY. Optional: HERMEVEN_AGENT_<ID>_PROFILE (default: the id) and
|
||||||
* HERMEVEN_AGENT_<ID>_NAME (default: the id, capitalised).
|
* 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[] {
|
function agentsFromEnv(env: NodeJS.ProcessEnv, baseUrl: string, defaultKey: string): AgentConfig[] {
|
||||||
|
const defaultName = agentName('HERMEVEN_AGENT_NAME', env.HERMEVEN_AGENT_NAME, 'Agent');
|
||||||
const agents: AgentConfig[] = [
|
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 ?? '')
|
const ids = (env.HERMEVEN_AGENTS ?? '')
|
||||||
.split(',')
|
.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`);
|
if (!apiKey) throw new ConfigError(`${prefix}_API_KEY is required: Hermes gives each profile its own API key`);
|
||||||
const profile = env[`${prefix}_PROFILE`] || id;
|
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`);
|
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({
|
const name = agentName(`${prefix}_NAME`, env[`${prefix}_NAME`], id.charAt(0).toUpperCase() + id.slice(1));
|
||||||
id,
|
agents.push({ id, name, baseUrl: `${baseUrl}/p/${profile}`, apiKey, wakeWords: wakeWords(`${prefix}_WAKE`, env[`${prefix}_WAKE`], name) });
|
||||||
name: agentName(`${prefix}_NAME`, env[`${prefix}_NAME`], id.charAt(0).toUpperCase() + id.slice(1)),
|
}
|
||||||
baseUrl: `${baseUrl}/p/${profile}`,
|
const claimed = new Map<string, string>();
|
||||||
apiKey,
|
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)');
|
if (agents.length > 16) throw new ConfigError('HERMEVEN_AGENTS lists too many agents (at most 15 besides the default)');
|
||||||
return agents;
|
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.
|
// One extra second of headroom over the capture cap for frame alignment.
|
||||||
audioMaxBytes: (captureMaxSeconds + 1) * AUDIO_FORMAT.bytesPerSecond,
|
audioMaxBytes: (captureMaxSeconds + 1) * AUDIO_FORMAT.bytesPerSecond,
|
||||||
turnsPerMinute: int(env, 'HERMEVEN_TURNS_PER_MINUTE', 20, 1, 600),
|
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),
|
pairingAttemptsPerMinute: int(env, 'HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE', 5, 1, 60),
|
||||||
},
|
},
|
||||||
credentials: {
|
credentials: {
|
||||||
|
|||||||
@@ -11,12 +11,14 @@ import {
|
|||||||
PairingClaimRequest,
|
PairingClaimRequest,
|
||||||
SCHEMA_VERSION,
|
SCHEMA_VERSION,
|
||||||
TextTurnRequest,
|
TextTurnRequest,
|
||||||
|
WakeQuery,
|
||||||
type ConversationResponse,
|
type ConversationResponse,
|
||||||
type DeviceCredential,
|
type DeviceCredential,
|
||||||
type DeviceStatusResponse,
|
type DeviceStatusResponse,
|
||||||
type ErrorCode,
|
type ErrorCode,
|
||||||
type ErrorResponse,
|
type ErrorResponse,
|
||||||
type Limits,
|
type Limits,
|
||||||
|
type WakeResponse,
|
||||||
} from '@hermeven/contracts';
|
} from '@hermeven/contracts';
|
||||||
import { DEFAULT_AGENT_ID, type BridgeConfig } from './config.ts';
|
import { DEFAULT_AGENT_ID, type BridgeConfig } from './config.ts';
|
||||||
import type { DeviceRow, Devices } from './devices.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 { RateLimiter } from './ratelimit.ts';
|
||||||
import type { SttAdapter } from './stt/adapter.ts';
|
import type { SttAdapter } from './stt/adapter.ts';
|
||||||
import type { TurnEngine } from './turns.ts';
|
import type { TurnEngine } from './turns.ts';
|
||||||
|
import { matchWake } from './wake.ts';
|
||||||
|
|
||||||
export interface ServerDeps {
|
export interface ServerDeps {
|
||||||
config: BridgeConfig;
|
config: BridgeConfig;
|
||||||
@@ -142,6 +145,9 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
|||||||
const pairingLimiter = new RateLimiter(config.limits.pairingAttemptsPerMinute, 60_000);
|
const pairingLimiter = new RateLimiter(config.limits.pairingAttemptsPerMinute, 60_000);
|
||||||
const turnLimiter = new RateLimiter(config.limits.turnsPerMinute, 60_000);
|
const turnLimiter = new RateLimiter(config.limits.turnsPerMinute, 60_000);
|
||||||
const readLimiter = new RateLimiter(600, 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 {
|
function authenticate(req: FastifyRequest): DeviceRow {
|
||||||
const header = req.headers.authorization ?? '';
|
const header = req.headers.authorization ?? '';
|
||||||
@@ -305,6 +311,48 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
|||||||
return engine.toResult(result.turn, result.replayed);
|
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) => {
|
app.get('/v1/turns/:requestId', async (req) => {
|
||||||
const device = authenticate(req);
|
const device = authenticate(req);
|
||||||
const { requestId } = req.params as { requestId: string };
|
const { requestId } = req.params as { requestId: string };
|
||||||
|
|||||||
@@ -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 };
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -100,6 +100,11 @@ export class FakeDevice implements DevicePort {
|
|||||||
connection(connected: boolean): void {
|
connection(connected: boolean): void {
|
||||||
for (const l of this.connectionListeners) l(connected);
|
for (const l of this.connectionListeners) l(connected);
|
||||||
}
|
}
|
||||||
|
/** Frames of digital silence, delivered like `speak`. Only while the mic is open. */
|
||||||
|
silence(seconds: number): void {
|
||||||
|
const frames = Math.round(seconds * 10);
|
||||||
|
for (let i = 0; i < frames && this.micOpen; i++) this.emit({ type: 'audio', pcm: new Uint8Array(3200) });
|
||||||
|
}
|
||||||
/** Deliver audio the way the SDK documents it: 100 ms frames of 3,200 bytes. Only while the mic is open. */
|
/** Deliver audio the way the SDK documents it: 100 ms frames of 3,200 bytes. Only while the mic is open. */
|
||||||
speak(seconds: number): void {
|
speak(seconds: number): void {
|
||||||
const frames = Math.round(seconds * 10);
|
const frames = Math.round(seconds * 10);
|
||||||
|
|||||||
@@ -0,0 +1,527 @@
|
|||||||
|
import { measureTextWrap } from '@evenrealities/pretext';
|
||||||
|
import { SCHEMA_VERSION } from '@hermeven/contracts';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import { Controller, type Snapshot } from '../../apps/even-client/src/core/controller.ts';
|
||||||
|
import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts';
|
||||||
|
import { FakeDevice } from '../fakes/fakeDevice.ts';
|
||||||
|
import { syntheticPcm } from '../fakes/fakeStt.ts';
|
||||||
|
import { createHarness, type Harness } from './harness.ts';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Listening for an agent's name. The bridge is real. Hermes, speech-to-text and the glasses are
|
||||||
|
* TEST FAKES: the "speech" is a tone, and what it "says" is whatever the fake recogniser is
|
||||||
|
* scripted to return. This proves the plumbing and the rules, and nothing about how well a
|
||||||
|
* real microphone or a real recogniser hears a name.
|
||||||
|
*/
|
||||||
|
const WENDY_KEY = 'wendy-profile-key-0123456789';
|
||||||
|
const CODY_KEY = 'cody-profile-key-0123456789';
|
||||||
|
const AGENT_ENV = {
|
||||||
|
HERMEVEN_AGENT_NAME: 'Pepper',
|
||||||
|
HERMEVEN_AGENTS: 'wendy,cody',
|
||||||
|
HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY,
|
||||||
|
HERMEVEN_AGENT_CODY_API_KEY: CODY_KEY,
|
||||||
|
HERMEVEN_AGENT_CODY_NAME: 'Cody R.',
|
||||||
|
HERMEVEN_AGENT_CODY_WAKE: 'kody',
|
||||||
|
};
|
||||||
|
|
||||||
|
let h: Harness;
|
||||||
|
async function harness(env: Record<string, string> = AGENT_ENV, opts: { stt?: boolean } = {}): Promise<void> {
|
||||||
|
h = await createHarness({ env, ...opts });
|
||||||
|
h.hermes.profiles.set('wendy', WENDY_KEY);
|
||||||
|
h.hermes.profiles.set('cody', CODY_KEY);
|
||||||
|
}
|
||||||
|
const wakeQuery = (extra: Record<string, string> = {}) =>
|
||||||
|
new URLSearchParams({ schema_version: '1', locale: 'en-US', encoding: 'pcm_s16le', sample_rate: '16000', channels: '1', ...extra });
|
||||||
|
const wake = (token: string | undefined, said: string, query = wakeQuery()) => {
|
||||||
|
h.stt.next({ text: said });
|
||||||
|
return h.api('POST', `/v1/wake?${query}`, { token, body: syntheticPcm(1) });
|
||||||
|
};
|
||||||
|
const runsPosted = () => h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs');
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await h?.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('bridge: POST /v1/wake', () => {
|
||||||
|
it('says who was addressed and what followed, and creates nothing', async () => {
|
||||||
|
await harness();
|
||||||
|
const { token } = await h.pair();
|
||||||
|
const res = await wake(token, ' Wendy, what is on my calendar?');
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body).toEqual({ schema_version: SCHEMA_VERSION, matched: true, agent_id: 'wendy', text: 'What is on my calendar?', near_miss: null });
|
||||||
|
expect((await wake(token, 'Kody.')).body).toMatchObject({ matched: true, agent_id: 'cody', text: '' });
|
||||||
|
expect((await wake(token, 'hey pepper turn it off')).body).toMatchObject({ matched: true, agent_id: 'default', text: 'Turn it off' });
|
||||||
|
// The recogniser got a proper WAV, as for a question.
|
||||||
|
expect(h.stt.lastWav).toMatchObject({ sampleRate: 16000, channels: 1, bitsPerSample: 16 });
|
||||||
|
expect(h.hermes.requests.filter((r) => r.method === 'POST')).toEqual([]);
|
||||||
|
expect(h.bridge.engine.activeConversation((await h.api('GET', '/v1/device', { token })).body.device_id)).toBeFalsy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('speech that is not for an agent is not returned, not kept and not logged', async () => {
|
||||||
|
await harness();
|
||||||
|
const { token } = await h.pair();
|
||||||
|
const secret = 'my card number is four one one one';
|
||||||
|
expect((await wake(token, secret)).body).toEqual({ schema_version: SCHEMA_VERSION, matched: false, agent_id: null, text: '', near_miss: null });
|
||||||
|
expect((await wake(token, `I told Wendy that ${secret}`)).body).toMatchObject({ matched: false, text: '' });
|
||||||
|
expect((await wake(token, 'Wendi, hello')).body).toEqual({ schema_version: SCHEMA_VERSION, matched: false, agent_id: null, text: '', near_miss: 'wendi' });
|
||||||
|
await wake(token, `Wendy, ${secret}`);
|
||||||
|
const logs = h.logs.join('\n');
|
||||||
|
for (const fragment of ['card number', 'four one one', 'wendi', 'Wendi']) expect(logs).not.toContain(fragment);
|
||||||
|
expect(logs).toContain('wake.matched');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('needs a device credential and a well-formed request', async () => {
|
||||||
|
await harness();
|
||||||
|
const { token } = await h.pair();
|
||||||
|
expect((await wake(undefined, 'Wendy')).status).toBe(401);
|
||||||
|
expect((await h.api('POST', `/v1/wake?${wakeQuery()}`, { token, json: { a: 1 } })).status).toBe(415);
|
||||||
|
expect((await wake(token, 'Wendy', wakeQuery({ sample_rate: '8000' }))).status).toBe(400);
|
||||||
|
expect((await wake(token, 'Wendy', wakeQuery({ schema_version: '2' }))).status).toBe(400);
|
||||||
|
expect((await h.api('POST', `/v1/wake?${wakeQuery()}`, { token, body: Buffer.alloc(3) })).status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a failed transcription is "nobody was addressed"', async () => {
|
||||||
|
await harness();
|
||||||
|
const { token } = await h.pair();
|
||||||
|
h.stt.next({ status: 500 });
|
||||||
|
const res = await h.api('POST', `/v1/wake?${wakeQuery()}`, { token, body: syntheticPcm(1) });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.matched).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers not_found when nobody can be called by voice', async () => {
|
||||||
|
await harness(AGENT_ENV, { stt: false });
|
||||||
|
expect((await wake((await h.pair()).token, 'Wendy')).status).toBe(404);
|
||||||
|
await h.close();
|
||||||
|
// One agent, never given a name: there is no word to listen for.
|
||||||
|
await harness({});
|
||||||
|
expect((await wake((await h.pair()).token, 'Agent, hello')).status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('checks one stretch of speech at a time per device, within a per-minute budget', async () => {
|
||||||
|
await harness({ ...AGENT_ENV, HERMEVEN_WAKE_CHECKS_PER_MINUTE: '2' });
|
||||||
|
const { token } = await h.pair();
|
||||||
|
h.stt.next({ text: 'hello', delayMs: 150 });
|
||||||
|
const first = h.api('POST', `/v1/wake?${wakeQuery()}`, { token, body: syntheticPcm(1) });
|
||||||
|
await new Promise((r) => setTimeout(r, 40));
|
||||||
|
expect((await h.api('POST', `/v1/wake?${wakeQuery()}`, { token, body: syntheticPcm(1) })).status).toBe(429);
|
||||||
|
expect((await first).status).toBe(200);
|
||||||
|
expect((await wake(token, 'hello')).status).toBe(200);
|
||||||
|
expect((await wake(token, 'hello')).status).toBe(429);
|
||||||
|
// Questions have their own budget.
|
||||||
|
const conversation = await h.conversation(token);
|
||||||
|
expect((await h.textTurn(token, conversation, 'still fine')).status).toBe(202);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ the app
|
||||||
|
let device: FakeDevice;
|
||||||
|
let controller: Controller;
|
||||||
|
let snapshot: Snapshot;
|
||||||
|
let sent: Array<{ method: string; path: string }>;
|
||||||
|
let wakeRoute: 'real' | 'not_found';
|
||||||
|
let extras: Partial<ConstructorParameters<typeof Controller>[0]>;
|
||||||
|
|
||||||
|
function makeController(dev: FakeDevice): Controller {
|
||||||
|
return new Controller({
|
||||||
|
wake: { armTimeoutMs: 250, watchMs: 40, stallMs: 150, retryMs: 120, pauseMs: 100 },
|
||||||
|
...extras,
|
||||||
|
device: dev,
|
||||||
|
measure: (text, width) => measureTextWrap(text, width).lineCount,
|
||||||
|
locale: 'en-US',
|
||||||
|
pollIntervalMs: 20,
|
||||||
|
submitAttempts: 3,
|
||||||
|
submitRetryMs: 30,
|
||||||
|
micStallMs: 2000,
|
||||||
|
makeClient: (baseUrl, token) =>
|
||||||
|
new BridgeClient({
|
||||||
|
baseUrl,
|
||||||
|
token,
|
||||||
|
timeoutMs: 1500,
|
||||||
|
fetchImpl: async (input, init) => {
|
||||||
|
const path = new URL(String(input)).pathname;
|
||||||
|
sent.push({ method: init?.method ?? 'GET', path });
|
||||||
|
if (path === '/v1/wake' && wakeRoute === 'not_found') {
|
||||||
|
return new Response(JSON.stringify({ schema_version: SCHEMA_VERSION, error: { code: 'not_found', message: 'Not found.', retryable: false } }), {
|
||||||
|
status: 404,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return fetch(input, init);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
onChange: (s) => {
|
||||||
|
snapshot = s;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise<void> {
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
while (!predicate()) {
|
||||||
|
if (Date.now() > deadline) throw new Error(`timed out waiting for: ${what}; phase=${snapshot?.state.phase} hud=${JSON.stringify(device.frame)}`);
|
||||||
|
await new Promise((r) => setTimeout(r, 10));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const phase = () => snapshot.state.phase;
|
||||||
|
const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const listening = () => until('listening for a name', () => device.micOpen && snapshot.state.wakeListening);
|
||||||
|
async function paired(): Promise<void> {
|
||||||
|
device = new FakeDevice();
|
||||||
|
controller = makeController(device);
|
||||||
|
await controller.start();
|
||||||
|
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
|
||||||
|
expect(phase()).toBe('ready');
|
||||||
|
}
|
||||||
|
/** Someone says something and stops: a tone, then a pause long enough to end the utterance. */
|
||||||
|
function say(seconds = 1, pauseSeconds = 0.8): void {
|
||||||
|
device.speak(seconds);
|
||||||
|
device.silence(pauseSeconds);
|
||||||
|
}
|
||||||
|
const posts = (path: string) => sent.filter((s) => s.method === 'POST' && s.path === path).length;
|
||||||
|
|
||||||
|
describe('glasses: always listening for a name', () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
sent = [];
|
||||||
|
wakeRoute = 'real';
|
||||||
|
extras = {};
|
||||||
|
await harness();
|
||||||
|
});
|
||||||
|
afterEach(async () => {
|
||||||
|
await controller?.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens the microphone by itself once paired, says so on the HUD, and stays on the glasses', async () => {
|
||||||
|
extras = { idleExit: { ready: 60, answer: 60, message: 60 } };
|
||||||
|
device = new FakeDevice();
|
||||||
|
controller = makeController(device);
|
||||||
|
await controller.start();
|
||||||
|
// Not paired: nothing to listen for, microphone closed.
|
||||||
|
await pause(60);
|
||||||
|
expect(device.micOpens).toBe(0);
|
||||||
|
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
|
||||||
|
await listening();
|
||||||
|
expect(device.frame).toEqual({
|
||||||
|
body: 'Pepper\n\nListening. Say a name, then your question:\nPepper · Wendy · Cody',
|
||||||
|
status: '● Tap: ask · Swipe: agent · 2×: exit',
|
||||||
|
});
|
||||||
|
expect(snapshot.wake).toEqual({ available: true, enabled: true, listening: true });
|
||||||
|
// Well past every idle time: still here, still listening.
|
||||||
|
await pause(250);
|
||||||
|
expect(device.exitAttempts).toBe(0);
|
||||||
|
expect(device.micOpen).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('"Wendy, <question>" in one breath is asked of Wendy, with what was heard shown while she works', async () => {
|
||||||
|
await paired();
|
||||||
|
await listening();
|
||||||
|
h.stt.next({ text: 'Wendy, what is on my calendar?' });
|
||||||
|
h.hermes.next({ kind: 'complete', afterMs: 200 });
|
||||||
|
say();
|
||||||
|
await until('thinking', () => phase() === 'thinking');
|
||||||
|
expect(device.frame.body).toBe('Wendy is thinking…\n\nHeard: What is on my calendar?');
|
||||||
|
// While the question is with the agent the microphone is closed.
|
||||||
|
await until('microphone closed', () => !device.micOpen);
|
||||||
|
expect(device.frame.status).not.toContain('●');
|
||||||
|
await until('answer', () => phase() === 'answer');
|
||||||
|
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||||
|
expect(snapshot.lastTurn?.input_text).toBe('What is on my calendar?');
|
||||||
|
// One recogniser call (the wake check); the question itself went as text, once.
|
||||||
|
expect(h.stt.calls).toBe(1);
|
||||||
|
expect(posts('/v1/turns')).toBe(1);
|
||||||
|
// Back at rest it listens again, on the answer screen too.
|
||||||
|
await listening();
|
||||||
|
expect(device.frame.status).toBe('● Wendy · Tap: ask');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a second name on the answer screen switches agent; each agent keeps its own conversation', async () => {
|
||||||
|
await paired();
|
||||||
|
await listening();
|
||||||
|
h.stt.next({ text: 'Wendy, first' });
|
||||||
|
say();
|
||||||
|
await until('answer', () => phase() === 'answer');
|
||||||
|
await listening();
|
||||||
|
h.stt.next({ text: 'Hey Kody, second' });
|
||||||
|
say();
|
||||||
|
await until('second answer', () => phase() === 'answer' && h.hermes.executedBy.length === 2);
|
||||||
|
await listening();
|
||||||
|
h.stt.next({ text: 'Wendy, third' });
|
||||||
|
say();
|
||||||
|
await until('third answer', () => phase() === 'answer' && h.hermes.executedBy.length === 3);
|
||||||
|
expect(h.hermes.executedBy).toEqual(['wendy', 'cody', 'wendy']);
|
||||||
|
expect([...h.hermes.sessions.values()].map((inputs) => inputs.length).sort()).toEqual([1, 2]);
|
||||||
|
expect(device.frame.status).toContain('Wendy · Tap: ask');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('speech that is not addressed to an agent goes nowhere and changes nothing on screen', async () => {
|
||||||
|
await paired();
|
||||||
|
await listening();
|
||||||
|
const frames = device.frames.length;
|
||||||
|
h.stt.next({ text: 'so I told Wendy we would be late' }, { text: 'Wendi, are you there' });
|
||||||
|
say();
|
||||||
|
await until('first check', () => h.stt.calls === 1);
|
||||||
|
await pause(80);
|
||||||
|
say();
|
||||||
|
await until('second check', () => h.stt.calls === 2);
|
||||||
|
await pause(80);
|
||||||
|
expect(phase()).toBe('ready');
|
||||||
|
expect(device.frames.length).toBe(frames);
|
||||||
|
expect(posts('/v1/turns')).toBe(0);
|
||||||
|
expect(posts('/v1/conversations')).toBe(0);
|
||||||
|
expect(runsPosted()).toEqual([]);
|
||||||
|
// The near miss is visible on the phone, as one word; the other sentence is nowhere.
|
||||||
|
const log = snapshot.log.map((e) => e.detail).join('\n');
|
||||||
|
expect(log).toContain('heard "wendi"');
|
||||||
|
expect(log).not.toContain('late');
|
||||||
|
expect(device.micOpen).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a name alone starts a recording that sends itself when the speaker stops', async () => {
|
||||||
|
await paired();
|
||||||
|
await listening();
|
||||||
|
h.stt.next({ text: 'Cody.' }, { text: 'are the tests passing' });
|
||||||
|
say(0.6);
|
||||||
|
await until('recording for Cody', () => phase() === 'listening');
|
||||||
|
expect(device.frame.body).toBe('Cody R. is listening…\n\nAsk your question. It is sent when you stop speaking.');
|
||||||
|
expect(device.frame.status).toContain('● REC');
|
||||||
|
// Going from listening to recording did not close and reopen the microphone.
|
||||||
|
expect(device.micOpens).toBe(1);
|
||||||
|
expect(device.micCloses).toBe(0);
|
||||||
|
device.speak(1.2);
|
||||||
|
device.silence(1);
|
||||||
|
expect(phase()).toBe('listening'); // a pause shorter than the limit does not send
|
||||||
|
device.silence(0.4);
|
||||||
|
await until('answer', () => phase() === 'answer');
|
||||||
|
expect(h.hermes.executedBy).toEqual(['cody']);
|
||||||
|
expect(snapshot.lastTurn?.input_text).toBe('are the tests passing');
|
||||||
|
await listening();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a question spoken before the name has been recognised is not lost', async () => {
|
||||||
|
await paired();
|
||||||
|
await listening();
|
||||||
|
h.stt.next({ text: 'Wendy', delayMs: 300 }, { text: 'what time is it' });
|
||||||
|
say(0.5);
|
||||||
|
await until('check started', () => posts('/v1/wake') === 1);
|
||||||
|
say(1.5); // spoken, and finished, while the name is still being checked
|
||||||
|
await until('answer', () => phase() === 'answer');
|
||||||
|
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||||
|
expect(snapshot.lastTurn?.input_text).toBe('what time is it');
|
||||||
|
expect(posts('/v1/wake')).toBe(1);
|
||||||
|
// What was sent as the question is at least the 1.5 s that was spoken.
|
||||||
|
expect(h.stt.lastWav!.dataBytes).toBeGreaterThanOrEqual(1.5 * 32000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a name alone followed by nothing goes back to rest and sends nothing', async () => {
|
||||||
|
await paired();
|
||||||
|
await listening();
|
||||||
|
h.stt.next({ text: 'Pepper' });
|
||||||
|
say(0.5);
|
||||||
|
await until('recording', () => phase() === 'listening');
|
||||||
|
await pause(300);
|
||||||
|
device.silence(0.2);
|
||||||
|
await until('ready', () => phase() === 'ready');
|
||||||
|
expect(posts('/v1/turns')).toBe(0);
|
||||||
|
expect(runsPosted()).toEqual([]);
|
||||||
|
await listening();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tapping still works while listening, and a tap during a check wins over what was heard', async () => {
|
||||||
|
await paired();
|
||||||
|
await listening();
|
||||||
|
h.stt.next({ text: 'Wendy, ignore this', delayMs: 250 }, { text: 'the tapped question' });
|
||||||
|
say();
|
||||||
|
await until('check started', () => posts('/v1/wake') === 1);
|
||||||
|
device.tap();
|
||||||
|
expect(phase()).toBe('listening');
|
||||||
|
device.speak(1);
|
||||||
|
await pause(350); // the check has come back by now
|
||||||
|
expect(phase()).toBe('listening');
|
||||||
|
expect(device.micOpens).toBe(1);
|
||||||
|
device.tap();
|
||||||
|
await until('answer', () => phase() === 'answer');
|
||||||
|
expect(h.hermes.executedBy).toEqual([null]);
|
||||||
|
expect(snapshot.lastTurn?.input_text).toBe('the tapped question');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a bridge that cannot do it ends hands free for the session, and says so', async () => {
|
||||||
|
wakeRoute = 'not_found';
|
||||||
|
await paired();
|
||||||
|
await listening();
|
||||||
|
say();
|
||||||
|
await until('microphone closed', () => !device.micOpen);
|
||||||
|
expect(snapshot.wake).toEqual({ available: false, enabled: false, listening: false });
|
||||||
|
expect(device.frame.body).toBe('Pepper\n\nHands free is not available.');
|
||||||
|
// Tap to ask still works.
|
||||||
|
device.tap();
|
||||||
|
await until('recording', () => phase() === 'listening' && device.micOpen);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a refused microphone is retried, and one that goes quiet is reopened', async () => {
|
||||||
|
device = new FakeDevice();
|
||||||
|
device.micAllowed = false;
|
||||||
|
controller = makeController(device);
|
||||||
|
await controller.start();
|
||||||
|
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
|
||||||
|
await pause(100);
|
||||||
|
expect(device.frame.status).not.toContain('●');
|
||||||
|
device.micAllowed = true;
|
||||||
|
await listening();
|
||||||
|
const opens = device.micOpens;
|
||||||
|
// No frames at all: the watchdog closes and reopens it.
|
||||||
|
await until('reopened', () => device.micOpens > opens, 2000);
|
||||||
|
expect(device.micOpen).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('closes the microphone when the glasses disconnect and when the app stops', async () => {
|
||||||
|
await paired();
|
||||||
|
await listening();
|
||||||
|
device.connection(false);
|
||||||
|
await until('closed on disconnect', () => !device.micOpen);
|
||||||
|
device.connection(true);
|
||||||
|
await listening();
|
||||||
|
await controller.stop();
|
||||||
|
expect(device.micOpen).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('without the option nothing listens: the microphone opens only on a tap', async () => {
|
||||||
|
extras = { wake: null, idleExit: null };
|
||||||
|
await paired();
|
||||||
|
await pause(100);
|
||||||
|
expect(device.micOpens).toBe(0);
|
||||||
|
expect(snapshot.wake).toEqual({ available: false, enabled: false, listening: false });
|
||||||
|
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('glasses: the opening menu', () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
sent = [];
|
||||||
|
wakeRoute = 'real';
|
||||||
|
extras = { menu: true, idleExit: null };
|
||||||
|
await harness();
|
||||||
|
});
|
||||||
|
afterEach(async () => {
|
||||||
|
await controller?.stop();
|
||||||
|
});
|
||||||
|
async function atMenu(): Promise<void> {
|
||||||
|
device = new FakeDevice();
|
||||||
|
controller = makeController(device);
|
||||||
|
await controller.start();
|
||||||
|
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
|
||||||
|
expect(phase()).toBe('menu');
|
||||||
|
}
|
||||||
|
|
||||||
|
it('opens on the menu with Hands free first, microphone closed, nothing sent', async () => {
|
||||||
|
await atMenu();
|
||||||
|
expect(device.frame).toEqual({ body: 'Hermeven\n\n> Hands free\n Agents', status: 'Tap: open · Swipe: move · 2×: exit' });
|
||||||
|
await pause(80);
|
||||||
|
expect(device.micOpens).toBe(0);
|
||||||
|
expect(snapshot.wake).toEqual({ available: true, enabled: false, listening: false });
|
||||||
|
device.speak(1);
|
||||||
|
expect(posts('/v1/wake') + posts('/v1/turns') + posts('/v1/conversations')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('one tap on the menu is hands free: listening, a name works, and double tap at Ready returns to the menu and closes the microphone', async () => {
|
||||||
|
await atMenu();
|
||||||
|
device.tap();
|
||||||
|
expect(phase()).toBe('ready');
|
||||||
|
await listening();
|
||||||
|
expect(device.frame).toEqual({
|
||||||
|
body: 'Pepper\n\nListening. Say a name, then your question:\nPepper · Wendy · Cody',
|
||||||
|
status: '● Tap: ask · Swipe: agent · 2×: menu',
|
||||||
|
});
|
||||||
|
h.stt.next({ text: 'Wendy, hello' });
|
||||||
|
say();
|
||||||
|
await until('answer', () => phase() === 'answer');
|
||||||
|
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||||
|
await listening();
|
||||||
|
device.doubleTap(); // answer -> Ready, still hands free
|
||||||
|
expect(phase()).toBe('ready');
|
||||||
|
expect(snapshot.wake.enabled).toBe(true);
|
||||||
|
device.doubleTap(); // Ready -> menu
|
||||||
|
expect(phase()).toBe('menu');
|
||||||
|
await until('microphone closed', () => !device.micOpen);
|
||||||
|
expect(device.exitRequests).toBe(0);
|
||||||
|
// Speech at the menu goes nowhere.
|
||||||
|
const checks = posts('/v1/wake');
|
||||||
|
device.speak(1);
|
||||||
|
await pause(60);
|
||||||
|
expect(posts('/v1/wake')).toBe(checks);
|
||||||
|
// The menu is the root page: double tap there asks the system to exit.
|
||||||
|
device.doubleTap();
|
||||||
|
expect(device.exitRequests).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Agents is the tap-to-ask app as before: no listening, the chosen agent, and it leaves when idle', async () => {
|
||||||
|
extras = { menu: true, idleExit: { ready: 150, answer: 150, message: 150 } };
|
||||||
|
await atMenu();
|
||||||
|
device.swipeDown();
|
||||||
|
expect(device.frame.body).toBe('Hermeven\n\n Hands free\n> Agents');
|
||||||
|
device.swipeDown(); // already on the last entry
|
||||||
|
device.tap();
|
||||||
|
expect(device.frame).toEqual({ body: 'Pepper\n\nReady.', status: 'Tap: ask · Swipe: agent · 2×: menu' });
|
||||||
|
device.swipeDown();
|
||||||
|
expect(device.frame.body).toBe('Wendy\n\nReady.');
|
||||||
|
say();
|
||||||
|
await pause(60);
|
||||||
|
expect(device.micOpens).toBe(0);
|
||||||
|
expect(posts('/v1/wake')).toBe(0);
|
||||||
|
h.stt.next({ text: 'a tapped question' });
|
||||||
|
device.tap();
|
||||||
|
await until('recording', () => phase() === 'listening' && device.micOpen);
|
||||||
|
device.speak(1);
|
||||||
|
device.tap();
|
||||||
|
await until('answer', () => phase() === 'answer');
|
||||||
|
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||||
|
await until('microphone closed', () => !device.micOpen);
|
||||||
|
expect(device.frame.status).not.toContain('●');
|
||||||
|
await until('left the glasses', () => device.exits === 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('an untouched menu leaves the glasses; hands free does not', async () => {
|
||||||
|
extras = { menu: true, idleExit: { ready: 80, answer: 80, message: 80 } };
|
||||||
|
await atMenu();
|
||||||
|
await until('left the glasses', () => device.exits === 1);
|
||||||
|
await controller.stop();
|
||||||
|
await atMenu();
|
||||||
|
device.tap();
|
||||||
|
await listening();
|
||||||
|
await pause(250);
|
||||||
|
expect(device.exitAttempts).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('where hands free cannot work the menu offers Agents only', async () => {
|
||||||
|
extras = { menu: true, wake: null, idleExit: null };
|
||||||
|
await atMenu();
|
||||||
|
expect(device.frame).toEqual({ body: 'Hermeven\n\n> Agents', status: 'Tap: open · Double-tap: exit' });
|
||||||
|
device.tap();
|
||||||
|
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||||
|
expect(device.micOpens).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a question still running when the app was closed is shown on reopening, not the menu; a typed question works from the menu', async () => {
|
||||||
|
await atMenu();
|
||||||
|
controller.askText('typed from the phone');
|
||||||
|
await until('answer', () => phase() === 'answer');
|
||||||
|
expect(snapshot.wake.enabled).toBe(false);
|
||||||
|
device.doubleTap();
|
||||||
|
device.doubleTap();
|
||||||
|
expect(phase()).toBe('menu');
|
||||||
|
h.hermes.next({ kind: 'complete', afterMs: 400 });
|
||||||
|
const polls = () => sent.filter((r) => r.method === 'GET' && r.path.startsWith('/v1/turns/')).length;
|
||||||
|
const before = polls();
|
||||||
|
controller.askText('a slow one');
|
||||||
|
// Accepted by the bridge and being polled: only then is there a turn to come back to.
|
||||||
|
await until('accepted and polling', () => phase() === 'thinking' && polls() > before);
|
||||||
|
await controller.stop();
|
||||||
|
const reborn = new FakeDevice();
|
||||||
|
for (const [k, v] of device.storage) reborn.storage.set(k, v);
|
||||||
|
device = reborn;
|
||||||
|
controller = makeController(device);
|
||||||
|
await controller.start();
|
||||||
|
expect(phase()).toBe('thinking');
|
||||||
|
await until('answer', () => phase() === 'answer');
|
||||||
|
expect(device.micOpens).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
@@ -155,7 +155,8 @@ async function launchSimulator(idleExit: 'off' | 'fast', code: string): Promise<
|
|||||||
automation = `http://127.0.0.1:${automationPort}`;
|
automation = `http://127.0.0.1:${automationPort}`;
|
||||||
const bin = require.resolve('@evenrealities/sim-linux-x64/bin/evenhub-simulator');
|
const bin = require.resolve('@evenrealities/sim-linux-x64/bin/evenhub-simulator');
|
||||||
// idleExit=off: this suite drives the app for longer than the idle timeout between steps.
|
// idleExit=off: this suite drives the app for longer than the idle timeout between steps.
|
||||||
const url = `${pageOrigin}/?idleExit=${idleExit}&bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`;
|
// wake=off, menu=off: this suite covers the tap path and idle exit from Ready, as before the menu.
|
||||||
|
const url = `${pageOrigin}/?idleExit=${idleExit}&wake=off&menu=off&bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`;
|
||||||
// alsa:null yields silence: the simulator never opens a real microphone in this test.
|
// alsa:null yields silence: the simulator never opens a real microphone in this test.
|
||||||
sim = spawn(bin, [url, '--automation-port', String(automationPort), '--no-glow', '--aid', 'alsa:null'], {
|
sim = spawn(bin, [url, '--automation-port', String(automationPort), '--no-glow', '--aid', 'alsa:null'], {
|
||||||
stdio: ['ignore', 'pipe', 'pipe'],
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
|||||||
Reference in New Issue
Block a user