import { createHash, randomUUID } from 'node:crypto'; import { isRetryable, SCHEMA_VERSION, type ErrorCode, type TurnOutcome, type TurnResult, type TurnState, } from '@hermeven/contracts'; import { DEFAULT_AGENT_ID, type BridgeConfig } from './config.ts'; import type { Db } from './db.ts'; import type { Devices } from './devices.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; /** Absolute time the agent must finish by; pushed back by time spent awaiting approval. */ agent_deadline_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; /** The configured agent this conversation is with. NULL = the default agent. */ agent_id: string | 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, msg: string): void; warn(fields: Record, msg: string): void; error(fields: Record, 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> = { 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(); private readonly tasks = new Set>(); private stopping = false; constructor( private readonly deps: { db: Db; config: BridgeConfig; devices: Devices; hermes: HermesAdapter; /** Adapters for the other configured agents, by id. The default one is `hermes`. */ agents?: ReadonlyMap; 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 /** True when `agentId` names an agent this bridge is configured to reach. */ knowsAgent(agentId: string): boolean { return agentId === DEFAULT_AGENT_ID || this.deps.agents?.has(agentId) === true; } /** The Hermes adapter for a conversation's agent, or undefined if it is no longer configured. */ private adapterFor(agentId: string | null): HermesAdapter | undefined { if (agentId === null || agentId === DEFAULT_AGENT_ID) return this.deps.hermes; return this.deps.agents?.get(agentId); } private adapterForTurn(row: TurnRow): HermesAdapter | undefined { const conversation = this.deps.db.prepare('SELECT agent_id FROM conversations WHERE id = ?').get(row.conversation_id) as | { agent_id: string | null } | undefined; return conversation ? this.adapterFor(conversation.agent_id) : undefined; } /** * Start a fresh conversation for the device with one agent. Any earlier conversation with * THAT agent is closed, not deleted; conversations with other agents are left open. */ createConversation(deviceId: string, agentId: string = DEFAULT_AGENT_ID): ConversationRow { const stored = agentId === DEFAULT_AGENT_ID ? null : agentId; const now = this.now(); const row: ConversationRow = { id: randomUUID(), device_id: deviceId, hermes_session_id: `hermeven-${randomUUID()}`, created_at: now, closed_at: null, agent_id: stored, }; this.deps.db.transaction(() => { this.deps.db .prepare('UPDATE conversations SET closed_at = ? WHERE device_id = ? AND closed_at IS NULL AND agent_id IS ?') .run(now, deviceId, stored); this.deps.db .prepare( 'INSERT INTO conversations (id, device_id, hermes_session_id, created_at, agent_id) VALUES (@id, @device_id, @hermes_session_id, @created_at, @agent_id)', ) .run(row); })(); this.deps.log.info({ device_id: deviceId, conversation_id: row.id, agent_id: agentId }, '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 AND agent_id 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, agent_deadline_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; } /** The id of the agent a turn was put to (`default` for the main one), or undefined if unknown. */ agentIdOf(row: TurnRow): string | undefined { const conversation = this.deps.db.prepare('SELECT agent_id FROM conversations WHERE id = ?').get(row.conversation_id) as | { agent_id: string | null } | undefined; return conversation ? (conversation.agent_id ?? DEFAULT_AGENT_ID) : undefined; } 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); } /** * Revoke a device and stop everything it has in flight. Access ends and the turns are * flagged in one transaction (Devices.revoke); this then acts on the flags at once. */ revokeDevice(deviceId: string): boolean { const revoked = this.deps.devices.revoke(deviceId); this.deps.log.info({ device_id: deviceId, revoked }, 'device.revoke_applied'); this.applyCancelFlags(); return revoked; } /** * Act on cancel flags set directly in the database: abort transcription and wake the worker * so it asks Hermes to stop. Runs right after an in-process revocation, and on a short * timer so a revocation made by the operator CLI (another process) is honoured promptly. */ applyCancelFlags(): number { if (this.active.size === 0) return 0; const flagged = this.deps.db .prepare("SELECT request_id FROM turns WHERE state != 'done' AND cancel_requested = 1") .all() as Array<{ request_id: string }>; let nudged = 0; for (const { request_id } of flagged) { const active = this.active.get(request_id); if (!active) continue; active.sttAbort?.abort(); active.wake?.(); nudged += 1; } return nudged; } /** 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 { 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): 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 = {}): 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 { 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 { 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. const agentStartedAt = this.now(); 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: agentStartedAt, agent_deadline_at: agentStartedAt + this.timing.agentDeadlineMs, }); } row = this.row(requestId)!; const hermes = this.adapterForTurn(row); if (!hermes) { // The conversation's agent was removed from the configuration. If anything may already // have been sent (a recovered turn), the outcome cannot be known from here. this.deps.log.warn({ request_id: requestId }, 'turn.agent_not_configured'); if (recovered && (row.hermes_run_id || row.pending_body)) this.finish(requestId, 'unknown', { code: 'outcome_unknown' }); else this.finish(requestId, 'failed', { code: 'agent_unreachable' }); return; } 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, hermes); if (runId === null) return; this.update(requestId, { hermes_run_id: runId, pending_body: null }); } await this.poll(requestId, active, hermes); } private async transcribe(requestId: string, pcm: Buffer, active: ActiveTurn, locale: string): Promise { 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, hermes: HermesAdapter): Promise { const row = this.row(requestId)!; const deadline = row.agent_deadline_at ?? (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 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, hermes: HermesAdapter): Promise { const start = this.row(requestId)!; const runId = start.hermes_run_id!; // Both clocks come from the database, so a bridge restart resumes them where they were: // the approval wait is measured from when the approval was first seen, and the agent // deadline keeps whatever pause earlier approvals earned it. let deadlineAt = start.agent_deadline_at ?? (start.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs; let approvalSince: number | null = start.approval_started_at; 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 hermes.stop(runId); stopAccepted = true; } catch (err) { if (!(err instanceof HermesUnavailableError)) throw err; } } let status: RunStatus | null = null; try { status = await 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) { // Recorded once, when the approval is first seen, and never moved afterwards. approvalSince = now; this.update(requestId, { approval_started_at: now }); } if (!stopReason) this.setState(requestId, 'approval_required'); break; default: if (approvalSince !== null) { // Approval was resolved on another surface; time spent waiting does not count. // Persisted in one write, so a restart cannot apply the pause twice or not at all. deadlineAt += now - approvalSince; approvalSince = null; this.update(requestId, { agent_deadline_at: deadlineAt, approval_started_at: 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); } } }