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
+611
View File
@@ -0,0 +1,611 @@
import { createHash, randomUUID } from 'node:crypto';
import {
isRetryable,
SCHEMA_VERSION,
type ErrorCode,
type TurnOutcome,
type TurnResult,
type TurnState,
} from '@hermeven/contracts';
import type { BridgeConfig } from './config.ts';
import type { Db } from './db.ts';
import {
buildRunBody,
HermesSubmitError,
HermesUnavailableError,
type HermesAdapter,
type RunStatus,
} from './hermes/adapter.ts';
import { SttError, type SttAdapter } from './stt/adapter.ts';
export interface TurnRow {
request_id: string;
device_id: string;
conversation_id: string;
input_kind: 'text' | 'audio';
input_fingerprint: string;
locale: string;
state: TurnState;
outcome: TurnOutcome | null;
error_code: ErrorCode | null;
error_message: string | null;
cancel_requested: 0 | 1;
hermes_idempotency_key: string;
hermes_run_id: string | null;
pending_body: string | null;
input_text: string | null;
answer_text: string | null;
created_at: number;
updated_at: number;
agent_started_at: number | null;
approval_started_at: number | null;
completed_at: number | null;
transcribe_ms: number | null;
agent_ms: number | null;
}
export interface ConversationRow {
id: string;
device_id: string;
hermes_session_id: string;
created_at: number;
closed_at: number | null;
}
export interface EngineTiming {
transcribeDeadlineMs: number;
agentDeadlineMs: number;
approvalWaitMs: number;
cancelGraceMs: number;
pollIntervalMs: number;
submitRetryMs: number;
/** Attempts before giving up when Hermes provably never received the request. */
notSentAttempts: number;
}
export function timingFromConfig(config: BridgeConfig): EngineTiming {
return {
transcribeDeadlineMs: config.limits.transcribeDeadlineSeconds * 1000,
agentDeadlineMs: config.limits.agentDeadlineSeconds * 1000,
approvalWaitMs: config.limits.approvalWaitSeconds * 1000,
cancelGraceMs: config.limits.cancelGraceSeconds * 1000,
pollIntervalMs: config.hermes.pollIntervalMs,
submitRetryMs: 500,
notSentAttempts: 3,
};
}
/** Structured, content-free logging: ids, states, codes and timings only. */
export interface EngineLog {
info(fields: Record<string, unknown>, msg: string): void;
warn(fields: Record<string, unknown>, msg: string): void;
error(fields: Record<string, unknown>, msg: string): void;
}
export type SubmitInput = { kind: 'text'; text: string } | { kind: 'audio'; pcm: Buffer };
export type SubmitResult =
| { ok: true; turn: TurnRow; replayed: boolean }
| { ok: false; code: ErrorCode; message: string };
interface ActiveTurn {
sttAbort: AbortController | null;
wake: (() => void) | null;
}
const MESSAGES: Partial<Record<ErrorCode, string>> = {
stt_unavailable: 'Speech-to-text is not available.',
stt_failed: 'Speech could not be transcribed.',
stt_timeout: 'Transcription took too long.',
stt_empty: 'No speech was recognised.',
interrupted_before_agent: 'The bridge restarted before the request reached the agent. Nothing ran.',
agent_unreachable: 'The agent could not be reached. Nothing ran.',
agent_rejected: 'The agent refused the request. Nothing ran.',
agent_failed: 'The agent reported a failure. Actions it had already taken are not undone.',
agent_interrupted: 'The agent was interrupted. Actions it had already taken are not undone.',
agent_timeout: 'The agent ran out of time and was stopped. Actions it had already taken are not undone.',
approval_timeout: 'The agent needed an approval that did not arrive, and was stopped.',
agent_incomplete: 'The agent stopped before finishing. This answer is partial.',
outcome_unknown: 'The outcome is unknown. Check the agent before asking again.',
};
export class TurnEngine {
private readonly active = new Map<string, ActiveTurn>();
private readonly tasks = new Set<Promise<void>>();
private stopping = false;
constructor(
private readonly deps: {
db: Db;
config: BridgeConfig;
hermes: HermesAdapter;
stt: SttAdapter;
log: EngineLog;
timing?: EngineTiming;
now?: () => number;
},
) {
this.timing = deps.timing ?? timingFromConfig(deps.config);
this.now = deps.now ?? Date.now;
}
private readonly timing: EngineTiming;
private readonly now: () => number;
// ------------------------------------------------------------ conversations
/** Start a fresh conversation for the device. Any earlier one is closed, not deleted. */
createConversation(deviceId: string): ConversationRow {
const now = this.now();
const row: ConversationRow = {
id: randomUUID(),
device_id: deviceId,
hermes_session_id: `hermeven-${randomUUID()}`,
created_at: now,
closed_at: null,
};
this.deps.db.transaction(() => {
this.deps.db.prepare('UPDATE conversations SET closed_at = ? WHERE device_id = ? AND closed_at IS NULL').run(now, deviceId);
this.deps.db
.prepare('INSERT INTO conversations (id, device_id, hermes_session_id, created_at) VALUES (@id, @device_id, @hermes_session_id, @created_at)')
.run(row);
})();
this.deps.log.info({ device_id: deviceId, conversation_id: row.id }, 'conversation.created');
return row;
}
activeConversation(deviceId: string): ConversationRow | undefined {
return this.deps.db
.prepare('SELECT * FROM conversations WHERE device_id = ? AND closed_at IS NULL ORDER BY created_at DESC LIMIT 1')
.get(deviceId) as ConversationRow | undefined;
}
// -------------------------------------------------------------------- turns
submit(
deviceId: string,
meta: { requestId: string; conversationId: string; locale: string },
input: SubmitInput,
): SubmitResult {
const db = this.deps.db;
const inputHash = createHash('sha256')
.update(input.kind === 'text' ? input.text : input.pcm)
.digest('hex');
const fingerprint = createHash('sha256')
.update([input.kind, meta.conversationId, meta.locale, inputHash].join('\n'))
.digest('hex');
const decision = db.transaction((): SubmitResult => {
const existing = db.prepare('SELECT * FROM turns WHERE request_id = ?').get(meta.requestId) as TurnRow | undefined;
if (existing) {
// Another device's request id is indistinguishable from a conflict on purpose.
if (existing.device_id !== deviceId || existing.input_fingerprint !== fingerprint) {
return { ok: false, code: 'request_id_conflict', message: 'This request id was already used for a different request.' };
}
return { ok: true, turn: existing, replayed: true };
}
const conversation = db.prepare('SELECT * FROM conversations WHERE id = ?').get(meta.conversationId) as ConversationRow | undefined;
if (!conversation || conversation.device_id !== deviceId) {
return { ok: false, code: 'not_found', message: 'Conversation not found.' };
}
if (conversation.closed_at !== null) {
return { ok: false, code: 'conversation_closed', message: 'This conversation was closed. Start a new one.' };
}
const busy = db
.prepare("SELECT 1 FROM turns WHERE conversation_id = ? AND state != 'done' LIMIT 1")
.get(meta.conversationId);
if (busy) {
return { ok: false, code: 'conversation_busy', message: 'The previous request is still in progress.' };
}
const now = this.now();
const row: TurnRow = {
request_id: meta.requestId,
device_id: deviceId,
conversation_id: meta.conversationId,
input_kind: input.kind,
input_fingerprint: fingerprint,
locale: meta.locale,
state: 'accepted',
outcome: null,
error_code: null,
error_message: null,
cancel_requested: 0,
// Derived from our own request id; opaque and unguessable enough (UUIDv4 inside).
hermes_idempotency_key: `hermeven-turn-${meta.requestId}`,
hermes_run_id: null,
pending_body: null,
input_text: input.kind === 'text' ? input.text : null,
answer_text: null,
created_at: now,
updated_at: now,
agent_started_at: null,
approval_started_at: null,
completed_at: null,
transcribe_ms: null,
agent_ms: null,
};
db.prepare(
`INSERT INTO turns (request_id, device_id, conversation_id, input_kind, input_fingerprint, locale, state,
hermes_idempotency_key, input_text, created_at, updated_at)
VALUES (@request_id, @device_id, @conversation_id, @input_kind, @input_fingerprint, @locale, @state,
@hermes_idempotency_key, @input_text, @created_at, @updated_at)`,
).run(row);
return { ok: true, turn: row, replayed: false };
})();
if (decision.ok && !decision.replayed) {
this.deps.log.info({ request_id: meta.requestId, input_kind: input.kind, state: 'accepted' }, 'turn.accepted');
this.launch(meta.requestId, input.kind === 'audio' ? input.pcm : null);
}
return decision;
}
get(deviceId: string, requestId: string): TurnRow | undefined {
const row = this.row(requestId);
return row && row.device_id === deviceId ? row : undefined;
}
/**
* Idempotent. Records the request and nudges the worker; the terminal outcome is whatever
* Hermes confirms. A cancel never claims that side effects were undone.
*/
cancel(deviceId: string, requestId: string): TurnRow | undefined {
const row = this.get(deviceId, requestId);
if (!row) return undefined;
if (row.state === 'done' || row.cancel_requested) return row;
this.update(requestId, { cancel_requested: 1 });
this.deps.log.info({ request_id: requestId, state: row.state }, 'turn.cancel_requested');
const active = this.active.get(requestId);
active?.sttAbort?.abort();
active?.wake?.();
return this.row(requestId);
}
/** Resume or settle every turn a previous process left in flight. Call once at startup. */
recover(): void {
const rows = this.deps.db.prepare("SELECT * FROM turns WHERE state != 'done'").all() as TurnRow[];
for (const row of rows) {
if (row.hermes_run_id || row.pending_body) {
this.deps.log.warn({ request_id: row.request_id, state: row.state }, 'turn.recovering');
this.launch(row.request_id, null, true);
} else {
// Audio lived only in memory and nothing had been sent to Hermes: provably nothing ran.
this.finish(row.request_id, 'failed', { code: 'interrupted_before_agent' });
}
}
}
/** Drop cached input/answer text past the retention window, and stale pairing codes. */
purgeExpired(): number {
const cutoff = this.now() - this.deps.config.resultRetentionSeconds * 1000;
const res = this.deps.db
.prepare(
`UPDATE turns SET input_text = NULL, answer_text = NULL
WHERE state = 'done' AND completed_at < ? AND (input_text IS NOT NULL OR answer_text IS NOT NULL)`,
)
.run(cutoff);
this.deps.db.prepare('DELETE FROM pairing_codes WHERE expires_at < ?').run(this.now() - 86_400_000);
return res.changes;
}
/** Stop workers without settling their turns; the next start recovers them. */
async shutdown(): Promise<void> {
this.stopping = true;
for (const active of this.active.values()) {
active.sttAbort?.abort();
active.wake?.();
}
await Promise.allSettled([...this.tasks]);
}
toResult(row: TurnRow, replayed = false): TurnResult {
const iso = (ms: number) => new Date(ms).toISOString();
return {
schema_version: SCHEMA_VERSION,
request_id: row.request_id,
conversation_id: row.conversation_id,
state: row.state,
terminal: row.state === 'done',
outcome: row.outcome,
cancel_requested: row.cancel_requested === 1,
input_text: row.input_text,
answer_text: row.answer_text,
error: row.error_code
? { code: row.error_code, message: row.error_message ?? '', retryable: isRetryable(row.error_code) }
: null,
replayed,
created_at: iso(row.created_at),
updated_at: iso(row.updated_at),
timings: { transcribe_ms: row.transcribe_ms, agent_ms: row.agent_ms },
};
}
// ---------------------------------------------------------------- internals
private row(requestId: string): TurnRow | undefined {
return this.deps.db.prepare('SELECT * FROM turns WHERE request_id = ?').get(requestId) as TurnRow | undefined;
}
private update(requestId: string, fields: Partial<TurnRow>): void {
const keys = Object.keys(fields);
const sets = [...keys.map((k) => `${k} = @${k}`), 'updated_at = @updated_at'].join(', ');
this.deps.db
.prepare(`UPDATE turns SET ${sets} WHERE request_id = @request_id`)
.run({ ...fields, updated_at: this.now(), request_id: requestId });
}
private setState(requestId: string, state: TurnState, extra: Partial<TurnRow> = {}): void {
const before = this.row(requestId);
if (!before || before.state === 'done') return;
if (before.state === state && Object.keys(extra).length === 0) return;
this.update(requestId, { state, ...extra });
if (before.state !== state) this.deps.log.info({ request_id: requestId, from: before.state, state }, 'turn.state');
}
private finish(
requestId: string,
outcome: TurnOutcome,
opts: { code?: ErrorCode; answer?: string | null } = {},
): void {
const before = this.row(requestId);
if (!before || before.state === 'done') return;
const now = this.now();
this.update(requestId, {
state: 'done',
outcome,
error_code: opts.code ?? null,
error_message: opts.code ? (MESSAGES[opts.code] ?? 'The request did not complete.') : null,
answer_text: opts.answer ?? null,
pending_body: null,
completed_at: now,
agent_ms: before.agent_started_at ? now - before.agent_started_at : null,
});
this.deps.log.info(
{
request_id: requestId,
outcome,
error_code: opts.code ?? null,
transcribe_ms: before.transcribe_ms,
agent_ms: before.agent_started_at ? now - before.agent_started_at : null,
total_ms: now - before.created_at,
},
'turn.done',
);
}
private launch(requestId: string, pcm: Buffer | null, recovered = false): void {
const active: ActiveTurn = { sttAbort: null, wake: null };
this.active.set(requestId, active);
const task = this.drive(requestId, pcm, active, recovered)
.catch((err: unknown) => {
this.deps.log.error({ request_id: requestId, err_name: err instanceof Error ? err.name : 'unknown' }, 'turn.worker_crashed');
const row = this.row(requestId);
// Once anything may have reached Hermes, a crash leaves the outcome unknown.
if (row && (row.hermes_run_id || row.pending_body)) this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
else this.finish(requestId, 'failed', { code: 'interrupted_before_agent' });
})
.finally(() => {
this.active.delete(requestId);
this.tasks.delete(task);
});
this.tasks.add(task);
}
private cancelRequested(requestId: string): boolean {
return this.row(requestId)?.cancel_requested === 1;
}
private sleep(active: ActiveTurn, ms: number): Promise<void> {
return new Promise((resolve) => {
const timer = setTimeout(done, ms);
function done() {
clearTimeout(timer);
active.wake = null;
resolve();
}
active.wake = done;
});
}
private async drive(requestId: string, pcm: Buffer | null, active: ActiveTurn, recovered: boolean): Promise<void> {
let row = this.row(requestId)!;
if (!recovered) {
if (row.input_kind === 'audio') {
const text = await this.transcribe(requestId, pcm!, active, row.locale);
pcm = null; // the only reference to the recording; let it be collected
if (text === null) return;
}
if (this.cancelRequested(requestId)) {
// Nothing has been sent to Hermes: this cancel is clean and complete.
this.finish(requestId, 'cancelled');
return;
}
row = this.row(requestId)!;
const conversation = this.deps.db
.prepare('SELECT * FROM conversations WHERE id = ?')
.get(row.conversation_id) as ConversationRow;
// Persist the exact body BEFORE the first network attempt, so a crash can replay it
// under the same idempotency key instead of guessing.
this.setState(requestId, 'thinking', {
pending_body: buildRunBody({
input: row.input_text ?? '',
sessionId: conversation.hermes_session_id,
instructions: this.deps.config.hermes.instructions,
}),
agent_started_at: this.now(),
});
}
row = this.row(requestId)!;
if (!row.hermes_run_id) {
// A recovered turn may already have been sent by the previous process.
const runId = await this.submitToHermes(requestId, active, recovered);
if (runId === null) return;
this.update(requestId, { hermes_run_id: runId, pending_body: null });
}
await this.poll(requestId, active);
}
private async transcribe(requestId: string, pcm: Buffer, active: ActiveTurn, locale: string): Promise<string | null> {
this.setState(requestId, 'transcribing');
const started = this.now();
const abort = new AbortController();
active.sttAbort = abort;
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
abort.abort();
}, this.timing.transcribeDeadlineMs);
try {
const text = await this.deps.stt.transcribe({ pcm, locale, signal: abort.signal });
if (this.stopping) return null;
if (!text) {
this.finish(requestId, 'failed', { code: 'stt_empty' });
return null;
}
this.update(requestId, { input_text: text, transcribe_ms: this.now() - started });
return text;
} catch (err) {
if (this.stopping) return null; // left in flight; recover() settles it honestly
if (timedOut) this.finish(requestId, 'failed', { code: 'stt_timeout' });
else if (this.cancelRequested(requestId)) this.finish(requestId, 'cancelled');
else if (err instanceof SttError && err.kind === 'unavailable') this.finish(requestId, 'failed', { code: 'stt_unavailable' });
else this.finish(requestId, 'failed', { code: 'stt_failed' });
return null;
} finally {
clearTimeout(timer);
active.sttAbort = null;
}
}
/** Returns the run id, or null when the turn was settled here. */
private async submitToHermes(requestId: string, active: ActiveTurn, maybeAlreadySent: boolean): Promise<string | null> {
const row = this.row(requestId)!;
const deadline = (row.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs;
let ambiguous = maybeAlreadySent;
let notSent = 0;
for (;;) {
if (this.stopping) return null;
try {
const { runId } = await this.deps.hermes.submit({
idempotencyKey: row.hermes_idempotency_key,
body: row.pending_body!,
});
return runId;
} catch (err) {
if (!(err instanceof HermesSubmitError)) throw err;
this.deps.log.warn({ request_id: requestId, kind: err.kind, http_status: err.httpStatus ?? null }, 'hermes.submit_failed');
if (err.kind === 'conflict') {
this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
return null;
}
if (err.kind === 'rejected') {
this.finish(requestId, 'failed', { code: 'agent_rejected' });
return null;
}
if (err.kind === 'ambiguous') ambiguous = true;
if (err.kind === 'not_sent' && !ambiguous && ++notSent >= this.timing.notSentAttempts) {
this.finish(requestId, 'failed', { code: 'agent_unreachable' });
return null;
}
}
if (!ambiguous && this.cancelRequested(requestId)) {
// Every attempt so far provably never reached Hermes.
this.finish(requestId, 'cancelled');
return null;
}
if (this.now() >= deadline) {
// Timeout is "unknown until reconciled", never permission to run again.
if (ambiguous) this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
else this.finish(requestId, 'failed', { code: 'agent_unreachable' });
return null;
}
await this.sleep(active, this.timing.submitRetryMs);
}
}
private async poll(requestId: string, active: ActiveTurn): Promise<void> {
const start = this.row(requestId)!;
const runId = start.hermes_run_id!;
let deadlineAt = (start.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs;
let approvalSince: number | null = null;
let stopReason: 'user' | 'agent_timeout' | 'approval_timeout' | null = null;
let stopAccepted = false;
let graceUntil = 0;
for (;;) {
if (this.stopping) return;
const now = this.now();
if (!stopReason) {
if (this.cancelRequested(requestId)) stopReason = 'user';
else if (approvalSince !== null && now >= approvalSince + this.timing.approvalWaitMs) stopReason = 'approval_timeout';
else if (approvalSince === null && now >= deadlineAt) stopReason = 'agent_timeout';
if (stopReason) {
graceUntil = now + this.timing.cancelGraceMs;
this.setState(requestId, 'cancelling');
}
}
if (stopReason && !stopAccepted) {
try {
await this.deps.hermes.stop(runId);
stopAccepted = true;
} catch (err) {
if (!(err instanceof HermesUnavailableError)) throw err;
}
}
let status: RunStatus | null = null;
try {
status = await this.deps.hermes.status(runId);
} catch (err) {
if (!(err instanceof HermesUnavailableError)) throw err;
}
if (status) {
switch (status.state) {
case 'completed':
this.finish(requestId, 'succeeded', { answer: status.output });
return;
case 'failed':
if (status.output && !status.finished) {
this.finish(requestId, 'incomplete', { code: 'agent_incomplete', answer: status.output });
} else {
this.finish(requestId, 'failed', { code: 'agent_failed' });
}
return;
case 'cancelled':
this.finish(requestId, 'cancelled', stopReason && stopReason !== 'user' ? { code: stopReason } : {});
return;
case 'interrupted':
this.finish(requestId, 'failed', { code: 'agent_interrupted' });
return;
case 'unknown':
case 'not_found':
this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
return;
case 'waiting_for_approval':
if (approvalSince === null) approvalSince = now;
if (!stopReason) this.setState(requestId, 'approval_required', { approval_started_at: now });
break;
default:
if (approvalSince !== null) {
// Approval was resolved on another surface; time spent waiting does not count.
deadlineAt += now - approvalSince;
approvalSince = null;
}
if (!stopReason) this.setState(requestId, 'thinking');
}
}
if (stopReason && this.now() >= graceUntil) {
// We asked Hermes to stop and could not confirm what happened.
this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
return;
}
await this.sleep(active, this.timing.pollIntervalMs);
}
}
}