First vertical slice: Even client, bridge, contract v1, tests, docs

Client (apps/even-client): pure interaction reducer with generation-based
stale-result rejection, HUD renderer, measured pagination, Even Hub SDK
0.0.16 adapter, bridge HTTP client, phone pairing/status/diagnostics page.

Bridge (services/bridge): device pairing and revocable expiring credentials,
turn engine with idempotent submit, cancel, deadlines and restart recovery,
Hermes Runs API adapter, OpenAI-compatible STT adapter, operator CLI.

Contract (packages/contracts): versioned schemas, types and error codes.

Tests: 122 unit/integration (fakes), 6 simulator scenarios (Even Hub
simulator 0.9.5), 9 scenarios against a real Hermes v0.23.1 gateway with a
stub model. No real STT, real model or physical device has been exercised;
see docs/test-evidence.md and docs/device-test-plan.md.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Dan
2026-11-18 18:21:49 -08:00
co-authored by Claude Fable 5.2
commit 4687cc0114
79 changed files with 11685 additions and 0 deletions
+663
View File
@@ -0,0 +1,663 @@
import { AUDIO_FORMAT, DEFAULT_LIMITS, type DeviceStatusResponse, type TurnResult } from '@hermeven/contracts';
import { MENU_ITEM, type DeviceEvent } from '../device/events.ts';
import type { DevicePort } from '../device/port.ts';
import { BridgeApiError, BridgeClient, BridgeNetworkError } from '../net/bridgeClient.ts';
import { BODY_BOX, HUD, renderHud } from './hud.ts';
import { paginate, type MeasureLines } from './paginate.ts';
import { toPlainText } from './plaintext.ts';
import { initialState, reduce, type AppEvent, type AppState, type Effect, type HudError } from './reducer.ts';
const STORAGE_KEY = 'hermeven.v1';
interface Stored {
bridgeUrl: string;
token: string;
deviceId: string;
tokenExpiresAt: string;
pairingExpiresAt: string;
conversationId: string | null;
/** A turn that was in flight; re-attached by polling after a restart, never resubmitted. */
activeRequestId: string | null;
}
export interface DiagEntry {
at: number;
kind: string;
detail: string;
}
export interface Snapshot {
state: AppState;
paired: boolean;
bridgeUrl: string;
deviceId: string;
tokenExpiresAt: string;
pairingExpiresAt: string;
status: DeviceStatusResponse | null;
hudReady: boolean;
/** Last settled turn, complete and untruncated, for the phone. */
lastTurn: TurnResult | null;
log: DiagEntry[];
}
export interface ControllerOptions {
device: DevicePort;
measure: MeasureLines;
locale: string;
newId?: () => string;
now?: () => number;
makeClient?: (baseUrl: string, token: string) => BridgeClient;
onChange?: (snapshot: Snapshot) => void;
/** Receives each diagnostic entry (ids, codes, timings; never content). */
onNote?: (entry: DiagEntry) => void;
pollIntervalMs?: number;
submitAttempts?: number;
submitRetryMs?: number;
/** No audio frames for this long while recording means the microphone is gone. */
micStallMs?: number;
}
interface Capture {
generation: number;
chunks: Uint8Array[];
bytes: number;
maxBytes: number;
lastFrameAt: number;
limitSent: boolean;
}
type PendingInput = { requestId: string; kind: 'text'; text: string } | { requestId: string; kind: 'audio'; pcm: Uint8Array };
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
export class Controller {
private state: AppState = initialState;
private stored: Stored | null = null;
private client: BridgeClient | null = null;
private status: DeviceStatusResponse | null = null;
private capture: Capture | null = null;
private micOpen = false;
private pending: PendingInput | null = null;
private lastTurn: TurnResult | null = null;
private hudReady = false;
private stopped = false;
private ticker: ReturnType<typeof setInterval> | null = null;
private readonly log: DiagEntry[] = [];
private readonly unsubscribers: Array<() => void> = [];
private readonly device: DevicePort;
private readonly now: () => number;
private readonly newId: () => string;
private readonly pollIntervalMs: number;
private readonly submitAttempts: number;
private readonly submitRetryMs: number;
private readonly micStallMs: number;
constructor(private readonly options: ControllerOptions) {
this.device = options.device;
this.now = options.now ?? Date.now;
this.newId = options.newId ?? (() => crypto.randomUUID());
this.pollIntervalMs = options.pollIntervalMs ?? 700;
this.submitAttempts = options.submitAttempts ?? 4;
this.submitRetryMs = options.submitRetryMs ?? 1500;
this.micStallMs = options.micStallMs ?? 3000;
}
// ------------------------------------------------------------------ public
async start(): Promise<void> {
this.stored = await this.load();
this.hudReady = await this.device.init(renderHud(this.state, this.now()));
this.note('hud', this.hudReady ? 'HUD page created' : 'HUD page was refused by the host');
this.unsubscribers.push(
this.device.onEvent((event) => this.onDeviceEvent(event)),
this.device.onConnection((connected) => {
this.note('glasses', connected ? 'connected' : 'disconnected');
this.dispatch({ type: 'glasses_status', connected });
}),
);
let captureMaxSeconds: number = DEFAULT_LIMITS.captureMaxSeconds;
if (this.stored) {
this.client = this.makeClient(this.stored.bridgeUrl, this.stored.token);
try {
this.status = await this.client.device();
captureMaxSeconds = this.status.limits.capture_max_seconds;
await this.maybeRenew();
} catch (err) {
if (err instanceof BridgeApiError && (err.body.code === 'unauthorized' || err.body.code === 'credential_expired')) {
this.note('auth', `stored credential rejected: ${err.body.code}`);
await this.forget();
} else {
this.note('bridge', `status check failed: ${describe(err)}`);
}
}
}
this.dispatch({
type: 'init',
paired: this.stored !== null,
conversationId: this.stored?.conversationId ?? null,
captureMaxSeconds,
resumeRequestId: this.stored?.activeRequestId ?? null,
});
}
/** Stop for good: every pending retry and poll loop winds down and nothing more is drawn or emitted. */
async stop(): Promise<void> {
this.stopped = true;
for (const off of this.unsubscribers.splice(0)) off();
this.stopTicker();
await this.closeMic();
}
snapshot(): Snapshot {
return {
state: this.state,
paired: this.stored !== null,
bridgeUrl: this.stored?.bridgeUrl ?? '',
deviceId: this.stored?.deviceId ?? '',
tokenExpiresAt: this.stored?.tokenExpiresAt ?? '',
pairingExpiresAt: this.stored?.pairingExpiresAt ?? '',
status: this.status,
hudReady: this.hudReady,
lastTurn: this.lastTurn,
log: [...this.log],
};
}
/** Explicit pairing from the phone. Throws with a user-presentable message on failure. */
async pair(bridgeUrl: string, code: string, deviceName: string): Promise<void> {
const client = this.makeClient(bridgeUrl, '');
const credential = await client.claim(code, deviceName);
client.token = credential.token;
this.client = client;
this.stored = {
bridgeUrl,
token: credential.token,
deviceId: credential.device_id,
tokenExpiresAt: credential.token_expires_at,
pairingExpiresAt: credential.pairing_expires_at,
conversationId: null,
activeRequestId: null,
};
await this.save();
this.note('pairing', `paired as ${credential.device_id}`);
let captureMaxSeconds: number = DEFAULT_LIMITS.captureMaxSeconds;
try {
this.status = await client.device();
captureMaxSeconds = this.status.limits.capture_max_seconds;
} catch (err) {
this.note('bridge', `status check failed: ${describe(err)}`);
}
this.dispatch({ type: 'init', paired: true, conversationId: null, captureMaxSeconds, resumeRequestId: null });
}
/** Disconnect: revoke the credential on the bridge, then clear everything held locally. */
async disconnect(): Promise<{ revoked: boolean }> {
let revoked = false;
try {
await this.client?.revoke();
revoked = true;
} catch (err) {
// Local state is cleared regardless; the phone tells the user to revoke on the bridge.
this.note('pairing', `remote revoke failed: ${describe(err)}`);
}
await this.forget();
this.dispatch({ type: 'unpaired' });
return { revoked };
}
async renew(): Promise<void> {
if (!this.client || !this.stored) return;
const credential = await this.client.renew();
this.client.token = credential.token;
this.stored = { ...this.stored, token: credential.token, tokenExpiresAt: credential.token_expires_at };
await this.save();
this.note('pairing', 'credential renewed');
this.emit();
}
async refreshStatus(): Promise<void> {
if (!this.client) return;
try {
this.status = await this.client.device();
} catch (err) {
this.note('bridge', `status check failed: ${describe(err)}`);
}
this.emit();
}
askText(text: string): void {
const trimmed = text.trim();
if (trimmed) this.dispatch({ type: 'submit_text', freshId: this.newId(), text: trimmed });
}
newConversation(): void {
this.dispatch({ type: 'new_conversation' });
}
cancel(): void {
this.dispatch({ type: 'cancel' });
}
dispatch(event: AppEvent): void {
if (this.stopped) return;
const before = this.state;
const step = reduce(before, event);
this.state = step.state;
if (before.phase !== step.state.phase) this.note('state', `${before.phase} -> ${step.state.phase}`);
for (const effect of step.effects) void this.run(effect);
this.render();
this.emit();
}
// ----------------------------------------------------------------- effects
private async run(effect: Effect): Promise<void> {
try {
switch (effect.type) {
case 'start_capture':
return await this.startCapture(effect.generation);
case 'stop_capture_and_submit':
return await this.stopCaptureAndSubmit(effect.generation, effect.requestId);
case 'discard_capture':
this.capture = null;
this.pending = null;
return await this.closeMic();
case 'submit_text':
this.pending = { requestId: effect.requestId, kind: 'text', text: effect.text };
return await this.submit(effect.generation, effect.requestId);
case 'resubmit':
return await this.submit(effect.generation, effect.requestId);
case 'poll':
return await this.poll(effect.generation, effect.requestId);
case 'cancel_turn':
return await this.cancelTurn(effect.requestId);
case 'create_conversation':
return await this.createConversation(effect.generation);
case 'exit_dialog':
return await this.device.requestExit();
}
} catch (err) {
this.note('internal', `effect ${effect.type} failed: ${describe(err)}`);
}
}
private async startCapture(generation: number): Promise<void> {
const capture: Capture = {
generation,
chunks: [],
bytes: 0,
maxBytes: this.state.captureMaxSeconds * AUDIO_FORMAT.bytesPerSecond,
lastFrameAt: this.now(),
limitSent: false,
};
this.capture = capture;
this.micOpen = true;
const ok = await this.device.startMic();
if (this.capture !== capture) {
// Cancelled while the microphone was opening.
if (!this.capture) await this.closeMic();
return;
}
if (!ok) {
this.capture = null;
this.micOpen = false;
this.dispatch({ type: 'capture_failed', generation, reason: 'mic_refused' });
return;
}
capture.lastFrameAt = this.now();
this.dispatch({ type: 'capture_started', generation, at: this.now() });
this.startTicker();
}
private onAudio(pcm: Uint8Array): void {
const capture = this.capture;
// Frames outside an active, current-generation capture are dropped on the floor.
if (!capture || capture.generation !== this.state.generation || this.state.phase !== 'listening') return;
capture.lastFrameAt = this.now();
const room = capture.maxBytes - capture.bytes;
if (room > 0) {
const chunk = pcm.length > room ? pcm.slice(0, room) : pcm.slice();
capture.chunks.push(chunk);
capture.bytes += chunk.length;
}
if (capture.bytes >= capture.maxBytes && !capture.limitSent) {
capture.limitSent = true;
this.note('capture', 'capture limit reached');
this.dispatch({ type: 'capture_limit', generation: capture.generation });
}
}
private async stopCaptureAndSubmit(generation: number, requestId: string): Promise<void> {
const capture = this.capture;
this.capture = null;
this.stopTicker();
await this.closeMic();
if (!capture || capture.generation !== generation) return;
const usable = capture.bytes - (capture.bytes % 2);
if (usable === 0) {
this.dispatch({ type: 'capture_failed', generation, reason: 'empty' });
return;
}
const pcm = new Uint8Array(usable);
let offset = 0;
for (const chunk of capture.chunks) {
const take = Math.min(chunk.length, usable - offset);
pcm.set(chunk.subarray(0, take), offset);
offset += take;
}
this.note('capture', `captured ${(usable / AUDIO_FORMAT.bytesPerSecond).toFixed(1)} s`);
this.pending = { requestId, kind: 'audio', pcm };
await this.submit(generation, requestId);
}
private async closeMic(): Promise<void> {
if (!this.micOpen) return;
this.micOpen = false;
this.stopTicker();
await this.device.stopMic();
}
private stale(generation: number): boolean {
return this.stopped || generation !== this.state.generation;
}
private async ensureConversation(): Promise<string> {
if (this.state.conversationId) return this.state.conversationId;
const created = await this.client!.createConversation();
if (this.stored) {
this.stored = { ...this.stored, conversationId: created.conversation_id };
await this.save();
}
this.dispatch({ type: 'conversation_created', generation: this.state.generation, conversationId: created.conversation_id });
return created.conversation_id;
}
private async submit(generation: number, requestId: string): Promise<void> {
const pending = this.pending;
if (!this.client || !pending || pending.requestId !== requestId) return;
for (let attempt = 1; ; attempt++) {
if (this.stale(generation)) return;
try {
const conversationId = await this.ensureConversation();
if (this.stale(generation)) return;
const base = { requestId, conversationId, locale: this.options.locale };
// The same request id on every attempt: the bridge deduplicates, so a retry after a
// lost response cannot create a second turn.
const result =
pending.kind === 'text'
? await this.client.submitText({ ...base, text: pending.text })
: await this.client.submitAudio({ ...base, pcm: pending.pcm });
if (this.pending === pending) this.pending = null;
if (this.stale(generation)) {
// Cancelled while the request was on the wire: the cancel may have beaten it there.
void this.cancelTurn(requestId);
return;
}
await this.setActiveRequest(requestId);
this.note('turn', `accepted ${requestId}${result.replayed ? ' (duplicate ignored by bridge)' : ''}`);
this.onResult(generation, result);
if (!result.terminal) await this.poll(generation, requestId);
return;
} catch (err) {
if (err instanceof BridgeApiError) {
this.note('turn', `rejected: ${err.body.code}`);
this.pending = null;
if (!this.stale(generation)) this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) });
await this.afterAuthFailure(err);
return;
}
if (!(err instanceof BridgeNetworkError)) throw err;
this.note('bridge', `submit attempt ${attempt} failed: ${err.message}`);
if (attempt >= this.submitAttempts) {
if (!this.stale(generation)) this.dispatch({ type: 'network_lost', generation, stage: 'submit' });
return;
}
await sleep(this.submitRetryMs);
}
}
}
private async poll(generation: number, requestId: string): Promise<void> {
if (!this.client) return;
let failures = 0;
for (;;) {
await sleep(failures ? Math.min(5000, this.pollIntervalMs * 2 ** Math.min(failures, 3)) : this.pollIntervalMs);
if (this.stale(generation)) return;
try {
const result = await this.client.getTurn(requestId);
if (this.stale(generation)) return;
if (failures >= 3) this.dispatch({ type: 'network_restored', generation });
failures = 0;
this.onResult(generation, result);
if (result.terminal) return;
} catch (err) {
if (this.stale(generation)) return;
if (err instanceof BridgeApiError) {
this.note('turn', `status rejected: ${err.body.code}`);
await this.setActiveRequest(null);
this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) });
await this.afterAuthFailure(err);
return;
}
if (!(err instanceof BridgeNetworkError)) throw err;
failures += 1;
if (failures === 3) {
this.note('bridge', 'lost contact while waiting for the answer');
this.dispatch({ type: 'network_lost', generation, stage: 'poll' });
}
}
}
}
private onResult(generation: number, result: TurnResult): void {
let pages: string[] | null = null;
if (result.terminal) {
this.lastTurn = result;
void this.setActiveRequest(null);
this.note(
'turn',
`done ${result.request_id}: ${result.outcome}${result.error ? ` (${result.error.code})` : ''}` +
` stt=${result.timings.transcribe_ms ?? '-'}ms agent=${result.timings.agent_ms ?? '-'}ms`,
);
if (result.outcome === 'succeeded' || result.outcome === 'incomplete') {
const plain = toPlainText(result.answer_text ?? '') || '(The agent returned no text.)';
const started = this.now();
pages = paginate(
plain,
{ width: BODY_BOX.innerWidth, maxLines: HUD.bodyLines, maxBytes: HUD.pageMaxBytes },
this.options.measure,
);
this.note('hud', `answer laid out on ${pages.length} page(s) in ${this.now() - started} ms`);
}
}
this.dispatch({ type: 'turn_update', generation, result, pages });
}
private async cancelTurn(requestId: string): Promise<void> {
await this.setActiveRequest(null);
if (!this.client) return;
for (let attempt = 1; attempt <= 3; attempt++) {
try {
const result = await this.client.cancelTurn(requestId);
this.note('turn', `cancel requested for ${requestId}; bridge state ${result.state}`);
return;
} catch (err) {
if (err instanceof BridgeApiError) {
// not_found: the request never reached the bridge, so there is nothing to cancel.
this.note('turn', `cancel answered ${err.body.code}`);
return;
}
await sleep(this.submitRetryMs);
}
}
this.note('turn', `cancel for ${requestId} could not be delivered; the agent may still be running`);
}
private async createConversation(generation: number): Promise<void> {
if (!this.client) return;
try {
const created = await this.client.createConversation();
if (this.stored) {
this.stored = { ...this.stored, conversationId: created.conversation_id };
await this.save();
}
this.note('conversation', `new conversation ${created.conversation_id}`);
this.dispatch({ type: 'conversation_created', generation, conversationId: created.conversation_id });
} catch (err) {
const error: HudError =
err instanceof BridgeApiError
? this.hudError(err)
: { code: 'network', hud: 'Could not reach the bridge.', retryable: true };
this.note('conversation', `create failed: ${describe(err)}`);
this.dispatch({ type: 'conversation_failed', generation, error });
if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
}
}
// ------------------------------------------------------------------ device
private onDeviceEvent(event: DeviceEvent): void {
switch (event.type) {
case 'audio':
return this.onAudio(event.pcm);
case 'tap':
return this.dispatch({ type: 'activate', freshId: this.newId() });
case 'double_tap':
return this.dispatch({ type: 'back' });
case 'swipe_down':
return this.dispatch({ type: 'next_page' });
case 'swipe_up':
return this.dispatch({ type: 'prev_page' });
case 'menu':
if (event.itemId === MENU_ITEM.NEW_CONVERSATION) return this.dispatch({ type: 'new_conversation' });
if (event.itemId === MENU_ITEM.CANCEL) return this.dispatch({ type: 'cancel' });
return;
case 'system_exit':
case 'abnormal_exit':
this.note('lifecycle', event.type);
return this.dispatch({ type: 'app_exit' });
case 'foreground_enter':
case 'foreground_exit':
// Also fired when the OS menu opens and closes; nothing is torn down here.
this.note('lifecycle', event.type);
return this.render();
}
}
private render(): void {
if (this.hudReady && !this.stopped) this.device.show(renderHud(this.state, this.now()));
}
private startTicker(): void {
this.stopTicker();
this.ticker = setInterval(() => {
const capture = this.capture;
if (capture && this.state.phase === 'listening' && this.now() - capture.lastFrameAt > this.micStallMs) {
// Permission loss or a suspended audio stream both look like silence on the wire.
this.note('capture', 'no audio frames; stopping capture');
this.dispatch({ type: 'capture_failed', generation: capture.generation, reason: 'mic_stalled' });
return;
}
this.render();
}, 1000);
}
private stopTicker(): void {
if (this.ticker) clearInterval(this.ticker);
this.ticker = null;
}
// ----------------------------------------------------------------- helpers
private makeClient(baseUrl: string, token: string): BridgeClient {
return this.options.makeClient?.(baseUrl, token) ?? new BridgeClient({ baseUrl, token });
}
private hudError(err: BridgeApiError): HudError {
const code = err.body.code;
if (code === 'unauthorized' || code === 'credential_expired') {
return { code, hud: 'Not connected. Pair again on your phone.', retryable: false };
}
if (code === 'conversation_closed') return { code, hud: 'Conversation ended. Start a new one from the menu.', retryable: false };
return { code, hud: err.body.message, retryable: err.body.retryable };
}
private async afterAuthFailure(err: BridgeApiError): Promise<void> {
if (err.body.code !== 'unauthorized') return;
// Revoked or unknown credential: holding on to it helps nobody.
await this.forget();
this.dispatch({ type: 'unpaired' });
}
private async maybeRenew(): Promise<void> {
if (!this.stored) return;
const remaining = Date.parse(this.stored.tokenExpiresAt) - this.now();
if (Number.isFinite(remaining) && remaining < 2 * 86_400_000) {
try {
await this.renew();
} catch (err) {
this.note('pairing', `renewal failed: ${describe(err)}`);
}
}
}
private async setActiveRequest(requestId: string | null): Promise<void> {
if (!this.stored || this.stored.activeRequestId === requestId) return;
this.stored = { ...this.stored, activeRequestId: requestId };
await this.save();
}
private async load(): Promise<Stored | null> {
try {
const raw = await this.device.storageGet(STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as Partial<Stored>;
if (typeof parsed.bridgeUrl !== 'string' || typeof parsed.token !== 'string' || !parsed.token) return null;
return {
bridgeUrl: parsed.bridgeUrl,
token: parsed.token,
deviceId: String(parsed.deviceId ?? ''),
tokenExpiresAt: String(parsed.tokenExpiresAt ?? ''),
pairingExpiresAt: String(parsed.pairingExpiresAt ?? ''),
conversationId: typeof parsed.conversationId === 'string' ? parsed.conversationId : null,
activeRequestId: typeof parsed.activeRequestId === 'string' ? parsed.activeRequestId : null,
};
} catch {
return null;
}
}
private async save(): Promise<void> {
await this.device.storageSet(STORAGE_KEY, this.stored ? JSON.stringify(this.stored) : '');
}
private async forget(): Promise<void> {
this.stored = null;
this.client = null;
this.status = null;
this.pending = null;
this.lastTurn = null;
await this.save();
}
/** Diagnostics for the phone only: ids, codes and timings. Never transcript or answer text. */
private note(kind: string, detail: string): void {
const entry = { at: this.now(), kind, detail };
this.log.push(entry);
this.options.onNote?.(entry);
if (this.log.length > 200) this.log.splice(0, this.log.length - 200);
}
private emit(): void {
if (this.stopped) return;
this.options.onChange?.(this.snapshot());
}
}
function describe(err: unknown): string {
if (err instanceof BridgeApiError) return `${err.body.code} (HTTP ${err.status})`;
if (err instanceof Error) return `${err.name}: ${err.message}`;
return 'unknown error';
}