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:
@@ -0,0 +1,83 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { pino, type Logger } from 'pino';
|
||||
import type { BridgeConfig } from './config.ts';
|
||||
import { openDb, type Db } from './db.ts';
|
||||
import { Devices } from './devices.ts';
|
||||
import type { HermesAdapter } from './hermes/adapter.ts';
|
||||
import { HermesRunsAdapter } from './hermes/runsAdapter.ts';
|
||||
import { buildServer } from './server.ts';
|
||||
import { NoSttAdapter, type SttAdapter } from './stt/adapter.ts';
|
||||
import { OpenAiCompatibleStt } from './stt/openaiCompatible.ts';
|
||||
import { TurnEngine, type EngineLog, type EngineTiming } from './turns.ts';
|
||||
|
||||
export interface Bridge {
|
||||
app: FastifyInstance;
|
||||
db: Db;
|
||||
devices: Devices;
|
||||
engine: TurnEngine;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Pino redaction: belt and braces, since we never pass these fields to the logger anyway. */
|
||||
export const LOG_REDACT = [
|
||||
'req.headers.authorization',
|
||||
'headers.authorization',
|
||||
'token',
|
||||
'code',
|
||||
'text',
|
||||
'input_text',
|
||||
'answer_text',
|
||||
'pending_body',
|
||||
'body',
|
||||
];
|
||||
|
||||
export function sttFromConfig(config: BridgeConfig): SttAdapter {
|
||||
if (config.stt.provider === 'openai-compatible') {
|
||||
return new OpenAiCompatibleStt({ baseUrl: config.stt.baseUrl, apiKey: config.stt.apiKey, model: config.stt.model });
|
||||
}
|
||||
return new NoSttAdapter();
|
||||
}
|
||||
|
||||
export async function createBridge(
|
||||
config: BridgeConfig,
|
||||
overrides: { hermes?: HermesAdapter; stt?: SttAdapter; timing?: EngineTiming; logger?: object | boolean } = {},
|
||||
): Promise<Bridge> {
|
||||
const db = openDb(config.dbPath);
|
||||
const hermes =
|
||||
overrides.hermes ??
|
||||
new HermesRunsAdapter({
|
||||
baseUrl: config.hermes.baseUrl,
|
||||
apiKey: config.hermes.apiKey,
|
||||
requestTimeoutMs: config.hermes.requestTimeoutMs,
|
||||
});
|
||||
const stt = overrides.stt ?? sttFromConfig(config);
|
||||
const devices = new Devices(db, config);
|
||||
|
||||
const given = overrides.logger;
|
||||
const logger: Logger =
|
||||
given && typeof given === 'object'
|
||||
? typeof (given as Logger).child === 'function'
|
||||
? (given as Logger)
|
||||
: pino(given as object)
|
||||
: pino({ level: 'silent' });
|
||||
const engine = new TurnEngine({ db, config, hermes, stt, log: logger as unknown as EngineLog, timing: overrides.timing });
|
||||
const app = await buildServer({ config, devices, hermes, stt, engine, logger });
|
||||
|
||||
engine.recover();
|
||||
engine.purgeExpired();
|
||||
const purge = setInterval(() => engine.purgeExpired(), 60_000);
|
||||
purge.unref();
|
||||
|
||||
return {
|
||||
app,
|
||||
db,
|
||||
devices,
|
||||
engine,
|
||||
async close() {
|
||||
clearInterval(purge);
|
||||
await app.close();
|
||||
await engine.shutdown();
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { ConfigError, loadConfig } from './config.ts';
|
||||
import { openDb } from './db.ts';
|
||||
import { Devices } from './devices.ts';
|
||||
import { loadEnvFile } from './env.ts';
|
||||
|
||||
/**
|
||||
* Operator CLI. It talks to the SQLite file directly, so there is no admin
|
||||
* surface on the network: whoever can run this on the bridge host is the owner.
|
||||
*/
|
||||
function usage(): never {
|
||||
console.error(
|
||||
[
|
||||
'Usage: npm run bridge:cli -- <command>',
|
||||
'',
|
||||
' pair Print a single-use pairing code for one new device',
|
||||
' devices List paired devices',
|
||||
' revoke <device-id> Revoke a device credential immediately',
|
||||
].join('\n'),
|
||||
);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
loadEnvFile();
|
||||
const config = loadConfig();
|
||||
const db = openDb(config.dbPath);
|
||||
const devices = new Devices(db, config);
|
||||
const [command, arg] = process.argv.slice(2);
|
||||
|
||||
switch (command) {
|
||||
case 'pair': {
|
||||
const { code, expiresAt } = devices.createPairingCode();
|
||||
const minutes = Math.round((expiresAt - Date.now()) / 60_000);
|
||||
console.log(`Pairing code: ${code}`);
|
||||
console.log(`Valid for ${minutes} minute(s), one device, one use. Any earlier unused code is now void.`);
|
||||
break;
|
||||
}
|
||||
case 'devices': {
|
||||
const rows = devices.list();
|
||||
if (!rows.length) console.log('No devices paired.');
|
||||
for (const d of rows) {
|
||||
const status = d.revoked_at
|
||||
? 'revoked'
|
||||
: d.pairing_expires_at <= Date.now()
|
||||
? 'pairing expired'
|
||||
: d.token_expires_at <= Date.now()
|
||||
? 'token expired'
|
||||
: 'active';
|
||||
const seen = d.last_seen_at ? new Date(d.last_seen_at).toISOString() : 'never';
|
||||
console.log(`${d.id} ${status.padEnd(15)} last seen ${seen} ${d.name}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'revoke': {
|
||||
if (!arg) usage();
|
||||
console.log(devices.revoke(arg) ? `Revoked ${arg}.` : `No active device ${arg}.`);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
usage();
|
||||
}
|
||||
db.close();
|
||||
}
|
||||
|
||||
try {
|
||||
main();
|
||||
} catch (err) {
|
||||
console.error(err instanceof ConfigError ? `Configuration error: ${err.message}` : err);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { AUDIO_FORMAT, DEFAULT_LIMITS } from '@hermeven/contracts';
|
||||
|
||||
export interface BridgeConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
dbPath: string;
|
||||
/** Exact browser origins allowed by CORS. Empty = no cross-origin browser access. */
|
||||
allowedOrigins: string[];
|
||||
/** Refuse to bind a non-loopback address without this (TLS must terminate in front). */
|
||||
allowNonLoopback: boolean;
|
||||
/** Trust X-Forwarded-For from a reverse proxy (only when one is actually in front). */
|
||||
trustProxy: boolean;
|
||||
hermes: {
|
||||
/** Base URL of the Hermes API server, e.g. http://127.0.0.1:8642 or .../p/<profile>. */
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
/** Label of the configured profile; devices are bound to it. Not sent to Hermes. */
|
||||
profileLabel: string;
|
||||
/** Per-request ephemeral instructions layered on the agent prompt. Empty disables. */
|
||||
instructions: string;
|
||||
pollIntervalMs: number;
|
||||
requestTimeoutMs: number;
|
||||
};
|
||||
stt: {
|
||||
provider: 'none' | 'openai-compatible';
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
model: string;
|
||||
};
|
||||
limits: {
|
||||
captureMaxSeconds: number;
|
||||
transcribeDeadlineSeconds: number;
|
||||
agentDeadlineSeconds: number;
|
||||
approvalWaitSeconds: number;
|
||||
cancelGraceSeconds: number;
|
||||
textMaxChars: number;
|
||||
audioMaxBytes: number;
|
||||
turnsPerMinute: number;
|
||||
pairingAttemptsPerMinute: number;
|
||||
};
|
||||
credentials: {
|
||||
tokenTtlSeconds: number;
|
||||
pairingTtlSeconds: number;
|
||||
pairingCodeTtlSeconds: number;
|
||||
pairingCodeMaxFailures: number;
|
||||
};
|
||||
/** How long input/answer text stays in the bridge's result cache. Hermes is the authority. */
|
||||
resultRetentionSeconds: number;
|
||||
logLevel: string;
|
||||
}
|
||||
|
||||
const DEFAULT_INSTRUCTIONS =
|
||||
'The user reads this reply on a small monochrome heads-up display. ' +
|
||||
'Answer in plain text without Markdown, tables, code fences or links. ' +
|
||||
'Lead with the direct answer in one or two short sentences, then add detail only if it is needed.';
|
||||
|
||||
export class ConfigError extends Error {
|
||||
override name = 'ConfigError';
|
||||
}
|
||||
|
||||
function int(env: NodeJS.ProcessEnv, key: string, fallback: number, min = 1, max = Number.MAX_SAFE_INTEGER): number {
|
||||
const raw = env[key];
|
||||
if (raw === undefined || raw === '') return fallback;
|
||||
const n = Number(raw);
|
||||
if (!Number.isInteger(n) || n < min || n > max) {
|
||||
throw new ConfigError(`${key} must be an integer between ${min} and ${max}`);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function bool(env: NodeJS.ProcessEnv, key: string, fallback = false): boolean {
|
||||
const raw = env[key];
|
||||
if (raw === undefined || raw === '') return fallback;
|
||||
if (['1', 'true', 'yes'].includes(raw.toLowerCase())) return true;
|
||||
if (['0', 'false', 'no'].includes(raw.toLowerCase())) return false;
|
||||
throw new ConfigError(`${key} must be true or false`);
|
||||
}
|
||||
|
||||
export function isLoopback(host: string): boolean {
|
||||
return host === 'localhost' || host === '::1' || /^127\./.test(host);
|
||||
}
|
||||
|
||||
function httpUrl(key: string, raw: string): string {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(raw);
|
||||
} catch {
|
||||
throw new ConfigError(`${key} is not a valid URL`);
|
||||
}
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new ConfigError(`${key} must be http(s)`);
|
||||
if (url.protocol === 'http:' && !isLoopback(url.hostname)) {
|
||||
throw new ConfigError(`${key} must use https outside loopback`);
|
||||
}
|
||||
return raw.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
const host = env.HERMEVEN_HOST || '127.0.0.1';
|
||||
const allowNonLoopback = bool(env, 'HERMEVEN_ALLOW_NON_LOOPBACK');
|
||||
if (!isLoopback(host) && !allowNonLoopback) {
|
||||
throw new ConfigError(
|
||||
'HERMEVEN_HOST is not loopback. Put a TLS-terminating proxy or private network in front and set ' +
|
||||
'HERMEVEN_ALLOW_NON_LOOPBACK=true to confirm.',
|
||||
);
|
||||
}
|
||||
|
||||
const hermesKey = env.HERMES_API_KEY || '';
|
||||
if (!hermesKey) throw new ConfigError('HERMES_API_KEY is required (the Hermes API server refuses to start without one)');
|
||||
|
||||
const allowedOrigins = (env.HERMEVEN_ALLOWED_ORIGINS || '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
for (const origin of allowedOrigins) {
|
||||
if (origin === '*' ) throw new ConfigError('HERMEVEN_ALLOWED_ORIGINS must list exact origins, not *');
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(origin);
|
||||
} catch {
|
||||
throw new ConfigError(`HERMEVEN_ALLOWED_ORIGINS entry is not an origin: ${origin}`);
|
||||
}
|
||||
if (parsed.origin !== origin) throw new ConfigError(`HERMEVEN_ALLOWED_ORIGINS entry must be scheme://host[:port]: ${origin}`);
|
||||
}
|
||||
|
||||
const sttProvider = (env.STT_PROVIDER || 'none') as BridgeConfig['stt']['provider'];
|
||||
if (sttProvider !== 'none' && sttProvider !== 'openai-compatible') {
|
||||
throw new ConfigError('STT_PROVIDER must be "none" or "openai-compatible"');
|
||||
}
|
||||
let sttBaseUrl = '';
|
||||
if (sttProvider === 'openai-compatible') {
|
||||
if (!env.STT_BASE_URL) throw new ConfigError('STT_BASE_URL is required for STT_PROVIDER=openai-compatible');
|
||||
if (!env.STT_MODEL) throw new ConfigError('STT_MODEL is required for STT_PROVIDER=openai-compatible');
|
||||
sttBaseUrl = httpUrl('STT_BASE_URL', env.STT_BASE_URL);
|
||||
}
|
||||
|
||||
const captureMaxSeconds = int(env, 'HERMEVEN_CAPTURE_MAX_SECONDS', DEFAULT_LIMITS.captureMaxSeconds, 1, 120);
|
||||
|
||||
return {
|
||||
host,
|
||||
port: int(env, 'HERMEVEN_PORT', 8787, 0, 65535),
|
||||
dbPath: env.HERMEVEN_DB_PATH || './data/hermeven.sqlite',
|
||||
allowedOrigins,
|
||||
allowNonLoopback,
|
||||
trustProxy: bool(env, 'HERMEVEN_TRUST_PROXY'),
|
||||
hermes: {
|
||||
baseUrl: httpUrl('HERMES_BASE_URL', env.HERMES_BASE_URL || 'http://127.0.0.1:8642'),
|
||||
apiKey: hermesKey,
|
||||
profileLabel: env.HERMES_PROFILE_LABEL || 'default',
|
||||
instructions: env.HERMEVEN_INSTRUCTIONS === undefined ? DEFAULT_INSTRUCTIONS : env.HERMEVEN_INSTRUCTIONS,
|
||||
pollIntervalMs: int(env, 'HERMES_POLL_INTERVAL_MS', 500, 20, 10_000),
|
||||
requestTimeoutMs: int(env, 'HERMES_REQUEST_TIMEOUT_MS', 10_000, 50, 120_000),
|
||||
},
|
||||
stt: {
|
||||
provider: sttProvider,
|
||||
baseUrl: sttBaseUrl,
|
||||
apiKey: env.STT_API_KEY || '',
|
||||
model: env.STT_MODEL || '',
|
||||
},
|
||||
limits: {
|
||||
captureMaxSeconds,
|
||||
transcribeDeadlineSeconds: int(env, 'HERMEVEN_TRANSCRIBE_DEADLINE_SECONDS', DEFAULT_LIMITS.transcribeDeadlineSeconds, 1, 300),
|
||||
agentDeadlineSeconds: int(env, 'HERMEVEN_AGENT_DEADLINE_SECONDS', DEFAULT_LIMITS.agentDeadlineSeconds, 1, 3600),
|
||||
approvalWaitSeconds: int(env, 'HERMEVEN_APPROVAL_WAIT_SECONDS', DEFAULT_LIMITS.approvalWaitSeconds, 1, 3600),
|
||||
cancelGraceSeconds: int(env, 'HERMEVEN_CANCEL_GRACE_SECONDS', 30, 1, 600),
|
||||
textMaxChars: DEFAULT_LIMITS.textMaxChars,
|
||||
// One extra second of headroom over the capture cap for frame alignment.
|
||||
audioMaxBytes: (captureMaxSeconds + 1) * AUDIO_FORMAT.bytesPerSecond,
|
||||
turnsPerMinute: int(env, 'HERMEVEN_TURNS_PER_MINUTE', 20, 1, 600),
|
||||
pairingAttemptsPerMinute: int(env, 'HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE', 5, 1, 60),
|
||||
},
|
||||
credentials: {
|
||||
tokenTtlSeconds: int(env, 'HERMEVEN_TOKEN_TTL_SECONDS', 7 * 86_400, 60),
|
||||
pairingTtlSeconds: int(env, 'HERMEVEN_PAIRING_TTL_SECONDS', 90 * 86_400, 60),
|
||||
pairingCodeTtlSeconds: int(env, 'HERMEVEN_PAIRING_CODE_TTL_SECONDS', 300, 30, 3600),
|
||||
pairingCodeMaxFailures: int(env, 'HERMEVEN_PAIRING_CODE_MAX_FAILURES', 5, 1, 20),
|
||||
},
|
||||
resultRetentionSeconds: int(env, 'HERMEVEN_RESULT_RETENTION_SECONDS', 900, 10, 86_400),
|
||||
logLevel: env.HERMEVEN_LOG_LEVEL || 'info',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
export type Db = Database.Database;
|
||||
|
||||
const MIGRATIONS: string[] = [
|
||||
`
|
||||
CREATE TABLE devices (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
profile TEXT NOT NULL,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
created_at INTEGER NOT NULL,
|
||||
token_expires_at INTEGER NOT NULL,
|
||||
pairing_expires_at INTEGER NOT NULL,
|
||||
revoked_at INTEGER,
|
||||
last_seen_at INTEGER
|
||||
);
|
||||
CREATE TABLE pairing_codes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
code_hash TEXT NOT NULL UNIQUE,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
used_at INTEGER,
|
||||
failed_attempts INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE conversations (
|
||||
id TEXT PRIMARY KEY,
|
||||
device_id TEXT NOT NULL REFERENCES devices(id),
|
||||
-- Opaque reference into Hermes. Generated by the bridge, never accepted from a client.
|
||||
hermes_session_id TEXT NOT NULL UNIQUE,
|
||||
created_at INTEGER NOT NULL,
|
||||
closed_at INTEGER
|
||||
);
|
||||
CREATE INDEX conversations_device ON conversations(device_id, closed_at);
|
||||
CREATE TABLE turns (
|
||||
request_id TEXT PRIMARY KEY,
|
||||
device_id TEXT NOT NULL REFERENCES devices(id),
|
||||
conversation_id TEXT NOT NULL REFERENCES conversations(id),
|
||||
input_kind TEXT NOT NULL,
|
||||
-- SHA-256 of metadata + input bytes: detects a reused request_id with a different payload.
|
||||
input_fingerprint TEXT NOT NULL,
|
||||
locale TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
outcome TEXT,
|
||||
error_code TEXT,
|
||||
error_message TEXT,
|
||||
cancel_requested INTEGER NOT NULL DEFAULT 0,
|
||||
hermes_idempotency_key TEXT NOT NULL,
|
||||
hermes_run_id TEXT,
|
||||
-- Exact Hermes request body, held only between "about to submit" and "run id persisted"
|
||||
-- so a crash in that window can replay the same idempotent request. Cleared afterwards.
|
||||
pending_body TEXT,
|
||||
-- Result cache, cleared after the retention window. Hermes stays the transcript authority.
|
||||
input_text TEXT,
|
||||
answer_text TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
agent_started_at INTEGER,
|
||||
approval_started_at INTEGER,
|
||||
completed_at INTEGER,
|
||||
transcribe_ms INTEGER,
|
||||
agent_ms INTEGER
|
||||
);
|
||||
CREATE INDEX turns_conversation ON turns(conversation_id, state);
|
||||
CREATE INDEX turns_state ON turns(state);
|
||||
`,
|
||||
];
|
||||
|
||||
export function openDb(path: string): Db {
|
||||
if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
|
||||
const db = new Database(path);
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
db.pragma('busy_timeout = 5000');
|
||||
migrate(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
function migrate(db: Db): void {
|
||||
const current = db.pragma('user_version', { simple: true }) as number;
|
||||
for (let v = current; v < MIGRATIONS.length; v++) {
|
||||
const sql = MIGRATIONS[v]!;
|
||||
db.transaction(() => {
|
||||
db.exec(sql);
|
||||
db.pragma(`user_version = ${v + 1}`);
|
||||
})();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { createHash, randomBytes, randomInt, randomUUID, timingSafeEqual } from 'node:crypto';
|
||||
import type { BridgeConfig } from './config.ts';
|
||||
import type { Db } from './db.ts';
|
||||
|
||||
export interface DeviceRow {
|
||||
id: string;
|
||||
name: string;
|
||||
profile: string;
|
||||
token_hash: string;
|
||||
created_at: number;
|
||||
token_expires_at: number;
|
||||
pairing_expires_at: number;
|
||||
revoked_at: number | null;
|
||||
last_seen_at: number | null;
|
||||
}
|
||||
|
||||
export type AuthFailure = 'unauthorized' | 'credential_expired';
|
||||
export type PairingFailure = 'pairing_invalid' | 'pairing_locked';
|
||||
|
||||
// No 0/O, 1/I/L: read aloud or typed on a phone without ambiguity. 31 symbols.
|
||||
const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
|
||||
const CODE_LENGTH = 10; // ~49.5 bits; with 5 total failures before lockout, guessing is not viable.
|
||||
|
||||
export function sha256(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
|
||||
function normalizeCode(code: string): string {
|
||||
return code.toUpperCase().replace(/[^A-Z0-9]/g, '');
|
||||
}
|
||||
|
||||
function newToken(): string {
|
||||
return `hvn_${randomBytes(32).toString('base64url')}`;
|
||||
}
|
||||
|
||||
export class Devices {
|
||||
constructor(
|
||||
private readonly db: Db,
|
||||
private readonly config: BridgeConfig,
|
||||
private readonly now: () => number = Date.now,
|
||||
) {}
|
||||
|
||||
/** Operator action (CLI): mint a single-use, time-limited pairing code. Invalidates older unused codes. */
|
||||
createPairingCode(): { code: string; expiresAt: number } {
|
||||
const code = Array.from({ length: CODE_LENGTH }, () => CODE_ALPHABET[randomInt(CODE_ALPHABET.length)]).join('');
|
||||
const now = this.now();
|
||||
const expiresAt = now + this.config.credentials.pairingCodeTtlSeconds * 1000;
|
||||
this.db.transaction(() => {
|
||||
this.db.prepare('UPDATE pairing_codes SET used_at = ? WHERE used_at IS NULL').run(now);
|
||||
this.db
|
||||
.prepare('INSERT INTO pairing_codes (code_hash, created_at, expires_at) VALUES (?, ?, ?)')
|
||||
.run(sha256(code), now, expiresAt);
|
||||
})();
|
||||
return { code: `${code.slice(0, 5)}-${code.slice(5)}`, expiresAt };
|
||||
}
|
||||
|
||||
/**
|
||||
* Exchange a pairing code for a device credential. A wrong guess counts against every
|
||||
* outstanding code, so the code is burned after a few failures regardless of who guessed.
|
||||
*/
|
||||
claimPairingCode(
|
||||
rawCode: string,
|
||||
deviceName: string,
|
||||
): { ok: true; device: DeviceRow; token: string } | { ok: false; reason: PairingFailure } {
|
||||
const now = this.now();
|
||||
const hash = sha256(normalizeCode(rawCode));
|
||||
return this.db.transaction(() => {
|
||||
const live = this.db
|
||||
.prepare('SELECT id, code_hash, failed_attempts FROM pairing_codes WHERE used_at IS NULL AND expires_at > ?')
|
||||
.all(now) as Array<{ id: number; code_hash: string; failed_attempts: number }>;
|
||||
const match = live.find((row) => safeEqualHex(row.code_hash, hash));
|
||||
if (!match) {
|
||||
let locked = false;
|
||||
for (const row of live) {
|
||||
const failures = row.failed_attempts + 1;
|
||||
if (failures >= this.config.credentials.pairingCodeMaxFailures) {
|
||||
this.db.prepare('UPDATE pairing_codes SET failed_attempts = ?, used_at = ? WHERE id = ?').run(failures, now, row.id);
|
||||
locked = true;
|
||||
} else {
|
||||
this.db.prepare('UPDATE pairing_codes SET failed_attempts = ? WHERE id = ?').run(failures, row.id);
|
||||
}
|
||||
}
|
||||
return { ok: false as const, reason: locked ? ('pairing_locked' as const) : ('pairing_invalid' as const) };
|
||||
}
|
||||
this.db.prepare('UPDATE pairing_codes SET used_at = ? WHERE id = ?').run(now, match.id);
|
||||
const token = newToken();
|
||||
const device: DeviceRow = {
|
||||
id: randomUUID(),
|
||||
name: deviceName,
|
||||
profile: this.config.hermes.profileLabel,
|
||||
token_hash: sha256(token),
|
||||
created_at: now,
|
||||
token_expires_at: now + this.config.credentials.tokenTtlSeconds * 1000,
|
||||
pairing_expires_at: now + this.config.credentials.pairingTtlSeconds * 1000,
|
||||
revoked_at: null,
|
||||
last_seen_at: now,
|
||||
};
|
||||
device.token_expires_at = Math.min(device.token_expires_at, device.pairing_expires_at);
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO devices (id, name, profile, token_hash, created_at, token_expires_at, pairing_expires_at, last_seen_at)
|
||||
VALUES (@id, @name, @profile, @token_hash, @created_at, @token_expires_at, @pairing_expires_at, @last_seen_at)`,
|
||||
)
|
||||
.run(device);
|
||||
return { ok: true as const, device, token };
|
||||
})();
|
||||
}
|
||||
|
||||
authenticate(token: string): { ok: true; device: DeviceRow } | { ok: false; reason: AuthFailure } {
|
||||
if (!token || token.length > 200) return { ok: false, reason: 'unauthorized' };
|
||||
const row = this.db.prepare('SELECT * FROM devices WHERE token_hash = ?').get(sha256(token)) as DeviceRow | undefined;
|
||||
if (!row || row.revoked_at !== null) return { ok: false, reason: 'unauthorized' };
|
||||
const now = this.now();
|
||||
if (row.token_expires_at <= now || row.pairing_expires_at <= now) return { ok: false, reason: 'credential_expired' };
|
||||
// A device is only valid for the profile this bridge is configured to serve.
|
||||
if (row.profile !== this.config.hermes.profileLabel) return { ok: false, reason: 'unauthorized' };
|
||||
this.db.prepare('UPDATE devices SET last_seen_at = ? WHERE id = ?').run(now, row.id);
|
||||
return { ok: true, device: row };
|
||||
}
|
||||
|
||||
/** Explicit renewal: rotates the token (the old one stops working immediately). */
|
||||
renew(deviceId: string): { device: DeviceRow; token: string } {
|
||||
const now = this.now();
|
||||
const token = newToken();
|
||||
const current = this.get(deviceId)!;
|
||||
const tokenExpiresAt = Math.min(now + this.config.credentials.tokenTtlSeconds * 1000, current.pairing_expires_at);
|
||||
this.db
|
||||
.prepare('UPDATE devices SET token_hash = ?, token_expires_at = ? WHERE id = ?')
|
||||
.run(sha256(token), tokenExpiresAt, deviceId);
|
||||
return { device: this.get(deviceId)!, token };
|
||||
}
|
||||
|
||||
revoke(deviceId: string): boolean {
|
||||
const now = this.now();
|
||||
return this.db.transaction(() => {
|
||||
const res = this.db.prepare('UPDATE devices SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL').run(now, deviceId);
|
||||
this.db.prepare('UPDATE conversations SET closed_at = ? WHERE device_id = ? AND closed_at IS NULL').run(now, deviceId);
|
||||
return res.changes > 0;
|
||||
})();
|
||||
}
|
||||
|
||||
get(deviceId: string): DeviceRow | undefined {
|
||||
return this.db.prepare('SELECT * FROM devices WHERE id = ?').get(deviceId) as DeviceRow | undefined;
|
||||
}
|
||||
|
||||
list(): DeviceRow[] {
|
||||
return this.db.prepare('SELECT * FROM devices ORDER BY created_at').all() as DeviceRow[];
|
||||
}
|
||||
}
|
||||
|
||||
function safeEqualHex(a: string, b: string): boolean {
|
||||
const ab = Buffer.from(a, 'hex');
|
||||
const bb = Buffer.from(b, 'hex');
|
||||
return ab.length === bb.length && timingSafeEqual(ab, bb);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
/**
|
||||
* Load server secrets from an ignored `.env` (never committed, see .env.example).
|
||||
* Variables already present in the environment win.
|
||||
*/
|
||||
export function loadEnvFile(): void {
|
||||
const explicit = process.env.HERMEVEN_ENV_FILE;
|
||||
const candidates = explicit ? [explicit] : [resolve(process.cwd(), '.env'), resolve(process.cwd(), '../../.env')];
|
||||
for (const path of candidates) {
|
||||
if (existsSync(path)) {
|
||||
process.loadEnvFile(path);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* The one seam between Hermeven and Hermes. Everything the bridge knows about
|
||||
* Hermes goes through this interface so the real HTTP adapter and the test
|
||||
* fake are interchangeable.
|
||||
*/
|
||||
|
||||
export type RunState =
|
||||
| 'queued'
|
||||
| 'running'
|
||||
| 'waiting_for_approval'
|
||||
| 'stopping'
|
||||
| 'completed'
|
||||
| 'failed'
|
||||
| 'cancelled'
|
||||
| 'interrupted'
|
||||
/** Hermes itself does not know whether the turn executed (owner restart). */
|
||||
| 'unknown'
|
||||
/** Hermes has no record of the run under our credential. */
|
||||
| 'not_found';
|
||||
|
||||
export interface RunStatus {
|
||||
state: RunState;
|
||||
/** Final answer text; may also accompany a `failed` state when the turn stopped short. */
|
||||
output: string;
|
||||
/** False when Hermes says the turn did not finish (budget exhausted, partial). */
|
||||
finished: boolean;
|
||||
/** Redacted diagnostic from Hermes. Never shown on the HUD, never logged by default. */
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface SubmitRequest {
|
||||
/** Forwarded as `Idempotency-Key`; an exact retry returns the original run. */
|
||||
idempotencyKey: string;
|
||||
/** Exact JSON body. Must be byte-identical on a retry or Hermes reports a conflict. */
|
||||
body: string;
|
||||
}
|
||||
|
||||
export type SubmitFailureKind =
|
||||
/** The request provably never reached Hermes (connection refused, DNS). Nothing ran. */
|
||||
| 'not_sent'
|
||||
/** Hermes answered and refused admission before running anything (4xx, 429, 503). */
|
||||
| 'rejected'
|
||||
| 'busy'
|
||||
/** Sent, but no usable answer came back. The turn may or may not have been admitted. */
|
||||
| 'ambiguous'
|
||||
/** The key is already bound to a different request. Never resend under a new key. */
|
||||
| 'conflict';
|
||||
|
||||
export class HermesSubmitError extends Error {
|
||||
override name = 'HermesSubmitError';
|
||||
constructor(
|
||||
readonly kind: SubmitFailureKind,
|
||||
message: string,
|
||||
readonly httpStatus?: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Status could not be read at all (network). Distinct from a `not_found` answer. */
|
||||
export class HermesUnavailableError extends Error {
|
||||
override name = 'HermesUnavailableError';
|
||||
}
|
||||
|
||||
export interface HermesAdapter {
|
||||
submit(request: SubmitRequest): Promise<{ runId: string }>;
|
||||
status(runId: string): Promise<RunStatus>;
|
||||
/** Ask Hermes to interrupt. Resolves once the request was accepted, not once it stopped. */
|
||||
stop(runId: string): Promise<void>;
|
||||
/** Cheap liveness probe; true only when Hermes answered healthy. */
|
||||
reachable(): Promise<boolean>;
|
||||
}
|
||||
|
||||
/** Build the exact body for POST /v1/runs. Key order is fixed so retries are byte-identical. */
|
||||
export function buildRunBody(args: { input: string; sessionId: string; instructions: string }): string {
|
||||
const body: Record<string, string> = { input: args.input, session_id: args.sessionId };
|
||||
if (args.instructions) body.instructions = args.instructions;
|
||||
return JSON.stringify(body);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import {
|
||||
HermesSubmitError,
|
||||
HermesUnavailableError,
|
||||
type HermesAdapter,
|
||||
type RunState,
|
||||
type RunStatus,
|
||||
type SubmitRequest,
|
||||
} from './adapter.ts';
|
||||
|
||||
/**
|
||||
* Hermes API server adapter using the Runs API (verified against hermes-agent
|
||||
* v0.23.1 source, see docs/compatibility.md):
|
||||
*
|
||||
* POST /v1/runs Idempotency-Key header, body {input, session_id, instructions}
|
||||
* -> 202 {run_id, status}; an exact retry replays the same run_id.
|
||||
* GET /v1/runs/{id} pollable status
|
||||
* POST /v1/runs/{id}/stop interrupt
|
||||
*
|
||||
* The Runs API is used instead of POST /v1/responses because Responses has no
|
||||
* cancel endpoint and no pollable in-flight status; see docs/decisions/0002.
|
||||
*/
|
||||
export class HermesRunsAdapter implements HermesAdapter {
|
||||
constructor(
|
||||
private readonly opts: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
requestTimeoutMs: number;
|
||||
fetchImpl?: typeof fetch;
|
||||
},
|
||||
) {}
|
||||
|
||||
private get fetch(): typeof fetch {
|
||||
return this.opts.fetchImpl ?? fetch;
|
||||
}
|
||||
|
||||
private headers(extra: Record<string, string> = {}): Record<string, string> {
|
||||
return { Authorization: `Bearer ${this.opts.apiKey}`, Accept: 'application/json', ...extra };
|
||||
}
|
||||
|
||||
async submit(request: SubmitRequest): Promise<{ runId: string }> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await this.fetch(`${this.opts.baseUrl}/v1/runs`, {
|
||||
method: 'POST',
|
||||
headers: this.headers({ 'Content-Type': 'application/json', 'Idempotency-Key': request.idempotencyKey }),
|
||||
body: request.body,
|
||||
signal: AbortSignal.timeout(this.opts.requestTimeoutMs),
|
||||
});
|
||||
} catch (err) {
|
||||
throw new HermesSubmitError(neverConnected(err) ? 'not_sent' : 'ambiguous', describe(err));
|
||||
}
|
||||
if (res.status === 202 || res.status === 200) {
|
||||
const json = (await safeJson(res)) as { run_id?: unknown } | null;
|
||||
if (json && typeof json.run_id === 'string' && json.run_id) return { runId: json.run_id };
|
||||
// Admitted but unreadable: the retry under the same key recovers the run id.
|
||||
throw new HermesSubmitError('ambiguous', 'Hermes accepted the run but returned no run_id', res.status);
|
||||
}
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
if (res.status === 409) throw new HermesSubmitError('conflict', 'Hermes refused the idempotency key', 409);
|
||||
if (res.status === 429 || res.status === 503) throw new HermesSubmitError('busy', `Hermes is busy (${res.status})`, res.status);
|
||||
if (res.status >= 400 && res.status < 500) {
|
||||
throw new HermesSubmitError('rejected', `Hermes rejected the request (${res.status})`, res.status);
|
||||
}
|
||||
// 5xx: the server may have admitted the run before failing to answer.
|
||||
throw new HermesSubmitError('ambiguous', `Hermes answered ${res.status}`, res.status);
|
||||
}
|
||||
|
||||
async status(runId: string): Promise<RunStatus> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await this.fetch(`${this.opts.baseUrl}/v1/runs/${encodeURIComponent(runId)}`, {
|
||||
headers: this.headers(),
|
||||
signal: AbortSignal.timeout(this.opts.requestTimeoutMs),
|
||||
});
|
||||
} catch (err) {
|
||||
throw new HermesUnavailableError(describe(err));
|
||||
}
|
||||
if (res.status === 404) {
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
return { state: 'not_found', output: '', finished: false, error: null };
|
||||
}
|
||||
if (!res.ok) {
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
throw new HermesUnavailableError(`Hermes status answered ${res.status}`);
|
||||
}
|
||||
const json = (await safeJson(res)) as Record<string, unknown> | null;
|
||||
if (!json || typeof json.status !== 'string') throw new HermesUnavailableError('Hermes status was not readable');
|
||||
return mapRunStatus(json);
|
||||
}
|
||||
|
||||
async stop(runId: string): Promise<void> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await this.fetch(`${this.opts.baseUrl}/v1/runs/${encodeURIComponent(runId)}/stop`, {
|
||||
method: 'POST',
|
||||
headers: this.headers({ 'Content-Type': 'application/json' }),
|
||||
body: '{}',
|
||||
signal: AbortSignal.timeout(this.opts.requestTimeoutMs),
|
||||
});
|
||||
} catch (err) {
|
||||
throw new HermesUnavailableError(describe(err));
|
||||
}
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
// 409 covers "not active" and "unknown execution": the status poll decides the outcome.
|
||||
if (!res.ok && res.status !== 409 && res.status !== 404) {
|
||||
throw new HermesUnavailableError(`Hermes stop answered ${res.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async reachable(): Promise<boolean> {
|
||||
try {
|
||||
const res = await this.fetch(`${this.opts.baseUrl}/health`, {
|
||||
signal: AbortSignal.timeout(Math.min(this.opts.requestTimeoutMs, 3000)),
|
||||
});
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const KNOWN_STATES: ReadonlySet<string> = new Set<RunState>([
|
||||
'queued',
|
||||
'running',
|
||||
'waiting_for_approval',
|
||||
'stopping',
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
'interrupted',
|
||||
'unknown',
|
||||
]);
|
||||
|
||||
export function mapRunStatus(json: Record<string, unknown>): RunStatus {
|
||||
const raw = String(json.status);
|
||||
// An unrecognised status is treated as still in flight; the deadline bounds the wait.
|
||||
const state = (KNOWN_STATES.has(raw) ? raw : 'running') as RunState;
|
||||
return {
|
||||
state,
|
||||
output: typeof json.output === 'string' ? json.output : '',
|
||||
finished: json.completed !== false && json.partial !== true,
|
||||
error: typeof json.error === 'string' ? json.error : null,
|
||||
};
|
||||
}
|
||||
|
||||
async function safeJson(res: Response): Promise<unknown> {
|
||||
try {
|
||||
return await res.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function describe(err: unknown): string {
|
||||
if (err instanceof Error) {
|
||||
const cause = (err as { cause?: { code?: string } }).cause;
|
||||
return cause?.code ? `${err.name}: ${cause.code}` : err.name;
|
||||
}
|
||||
return 'request failed';
|
||||
}
|
||||
|
||||
/** True only when the socket was never established, so no request bytes reached Hermes. */
|
||||
function neverConnected(err: unknown): boolean {
|
||||
const code = (err as { cause?: { code?: string } })?.cause?.code;
|
||||
return code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'EAI_AGAIN' || code === 'EHOSTUNREACH' || code === 'ENETUNREACH';
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { LOG_REDACT, createBridge } from './app.ts';
|
||||
import { ConfigError, loadConfig } from './config.ts';
|
||||
import { loadEnvFile } from './env.ts';
|
||||
|
||||
async function main(): Promise<void> {
|
||||
loadEnvFile();
|
||||
const config = loadConfig();
|
||||
const bridge = await createBridge(config, {
|
||||
logger: { level: config.logLevel, redact: { paths: LOG_REDACT, censor: '[redacted]' } },
|
||||
});
|
||||
await bridge.app.listen({ host: config.host, port: config.port });
|
||||
|
||||
let closing = false;
|
||||
const stop = (signal: string) => {
|
||||
if (closing) return;
|
||||
closing = true;
|
||||
bridge.app.log.info({ signal }, 'bridge.stopping');
|
||||
bridge.close().then(
|
||||
() => process.exit(0),
|
||||
() => process.exit(1),
|
||||
);
|
||||
};
|
||||
process.on('SIGINT', () => stop('SIGINT'));
|
||||
process.on('SIGTERM', () => stop('SIGTERM'));
|
||||
}
|
||||
|
||||
main().catch((err: unknown) => {
|
||||
// Configuration problems are operator-facing; never print the environment.
|
||||
console.error(err instanceof ConfigError ? `Configuration error: ${err.message}` : err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
/** Fixed-window, in-memory limiter. Single-process by design (single-user MVP). */
|
||||
export class RateLimiter {
|
||||
private readonly windows = new Map<string, { start: number; count: number }>();
|
||||
|
||||
constructor(
|
||||
private readonly max: number,
|
||||
private readonly windowMs: number,
|
||||
private readonly now: () => number = Date.now,
|
||||
) {}
|
||||
|
||||
/** Returns false when the caller is over budget. */
|
||||
take(key: string): boolean {
|
||||
const now = this.now();
|
||||
const current = this.windows.get(key);
|
||||
if (!current || now - current.start >= this.windowMs) {
|
||||
if (this.windows.size > 10_000) this.sweep(now);
|
||||
this.windows.set(key, { start: now, count: 1 });
|
||||
return true;
|
||||
}
|
||||
if (current.count >= this.max) return false;
|
||||
current.count += 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
private sweep(now: number): void {
|
||||
for (const [key, w] of this.windows) if (now - w.start >= this.windowMs) this.windows.delete(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
import cors from '@fastify/cors';
|
||||
import Fastify, { LogController, type FastifyBaseLogger, type FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify';
|
||||
import {
|
||||
AUDIO_FORMAT,
|
||||
AudioTurnQuery,
|
||||
check,
|
||||
ConversationCreateRequest,
|
||||
httpStatusFor,
|
||||
isRetryable,
|
||||
PairingClaimRequest,
|
||||
SCHEMA_VERSION,
|
||||
TextTurnRequest,
|
||||
type ConversationResponse,
|
||||
type DeviceCredential,
|
||||
type DeviceStatusResponse,
|
||||
type ErrorCode,
|
||||
type ErrorResponse,
|
||||
type Limits,
|
||||
} from '@hermeven/contracts';
|
||||
import type { BridgeConfig } from './config.ts';
|
||||
import type { DeviceRow, Devices } from './devices.ts';
|
||||
import type { HermesAdapter } from './hermes/adapter.ts';
|
||||
import { RateLimiter } from './ratelimit.ts';
|
||||
import type { SttAdapter } from './stt/adapter.ts';
|
||||
import type { TurnEngine } from './turns.ts';
|
||||
|
||||
export interface ServerDeps {
|
||||
config: BridgeConfig;
|
||||
devices: Devices;
|
||||
engine: TurnEngine;
|
||||
hermes: HermesAdapter;
|
||||
stt: SttAdapter;
|
||||
/** Request bodies, queries and auth headers are never passed to it. */
|
||||
logger: FastifyBaseLogger;
|
||||
}
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
||||
|
||||
class ApiError extends Error {
|
||||
constructor(
|
||||
readonly code: ErrorCode,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
function errorBody(code: ErrorCode, message: string): ErrorResponse {
|
||||
return { schema_version: SCHEMA_VERSION, error: { code, message, retryable: isRetryable(code) } };
|
||||
}
|
||||
|
||||
function iso(ms: number): string {
|
||||
return new Date(ms).toISOString();
|
||||
}
|
||||
|
||||
export function effectiveLimits(config: BridgeConfig): Limits {
|
||||
return {
|
||||
capture_max_seconds: config.limits.captureMaxSeconds,
|
||||
transcribe_deadline_seconds: config.limits.transcribeDeadlineSeconds,
|
||||
agent_deadline_seconds: config.limits.agentDeadlineSeconds,
|
||||
approval_wait_seconds: config.limits.approvalWaitSeconds,
|
||||
audio_max_bytes: config.limits.audioMaxBytes,
|
||||
text_max_chars: config.limits.textMaxChars,
|
||||
};
|
||||
}
|
||||
|
||||
export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
const { config, devices, engine } = deps;
|
||||
const app = Fastify({
|
||||
loggerInstance: deps.logger,
|
||||
trustProxy: config.trustProxy,
|
||||
// JSON bodies are tiny; the audio parser below sets its own, larger limit.
|
||||
bodyLimit: 32 * 1024,
|
||||
// Per-request access logs are off: routes log ids and outcomes themselves, and a URL
|
||||
// can carry request metadata we do not want duplicated into logs.
|
||||
logController: new LogController({ disableRequestLogging: true }),
|
||||
// Fastify's default id is a counter; ours never contains client-supplied text.
|
||||
genReqId: () => crypto.randomUUID(),
|
||||
});
|
||||
|
||||
// Exact-origin CORS. CORS only tells browsers who may read answers; every route
|
||||
// except /healthz and the pairing claim still requires a device credential.
|
||||
await app.register(cors, {
|
||||
origin: config.allowedOrigins.length ? config.allowedOrigins : false,
|
||||
methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
|
||||
allowedHeaders: ['Authorization', 'Content-Type'],
|
||||
credentials: false,
|
||||
maxAge: 600,
|
||||
});
|
||||
|
||||
app.addHook('onSend', async (_req, reply) => {
|
||||
reply.header('X-Content-Type-Options', 'nosniff');
|
||||
reply.header('Cache-Control', 'no-store');
|
||||
reply.header('Referrer-Policy', 'no-referrer');
|
||||
});
|
||||
|
||||
// Raw audio: buffered in memory with a hard cap, never parsed as JSON, never written to disk.
|
||||
app.addContentTypeParser(
|
||||
'application/octet-stream',
|
||||
{ parseAs: 'buffer', bodyLimit: config.limits.audioMaxBytes },
|
||||
(_req, body, done) => done(null, body),
|
||||
);
|
||||
|
||||
app.setErrorHandler((err: Error & { statusCode?: number; code?: string }, req, reply) => {
|
||||
if (err instanceof ApiError) {
|
||||
return reply.code(httpStatusFor(err.code)).send(errorBody(err.code, err.message));
|
||||
}
|
||||
if (err.code === 'FST_ERR_CTP_BODY_TOO_LARGE' || err.statusCode === 413) {
|
||||
return reply.code(413).send(errorBody('payload_too_large', 'Request body is too large.'));
|
||||
}
|
||||
if (err.code === 'FST_ERR_CTP_INVALID_MEDIA_TYPE' || err.statusCode === 415) {
|
||||
return reply.code(415).send(errorBody('unsupported_media', 'Unsupported content type.'));
|
||||
}
|
||||
if (err.statusCode && err.statusCode >= 400 && err.statusCode < 500) {
|
||||
return reply.code(400).send(errorBody('invalid_request', 'Malformed request.'));
|
||||
}
|
||||
req.log.error({ err_name: err.name, err_code: err.code ?? null }, 'request.failed');
|
||||
return reply.code(500).send(errorBody('internal', 'Internal error.'));
|
||||
});
|
||||
app.setNotFoundHandler((_req, reply) => reply.code(404).send(errorBody('not_found', 'Not found.')));
|
||||
|
||||
const pairingLimiter = new RateLimiter(config.limits.pairingAttemptsPerMinute, 60_000);
|
||||
const turnLimiter = new RateLimiter(config.limits.turnsPerMinute, 60_000);
|
||||
const readLimiter = new RateLimiter(600, 60_000);
|
||||
|
||||
function authenticate(req: FastifyRequest): DeviceRow {
|
||||
const header = req.headers.authorization ?? '';
|
||||
const token = header.startsWith('Bearer ') ? header.slice(7).trim() : '';
|
||||
const result = devices.authenticate(token);
|
||||
if (!result.ok) {
|
||||
throw new ApiError(
|
||||
result.reason,
|
||||
result.reason === 'credential_expired' ? 'Credential expired. Renew or pair again.' : 'Not authorized.',
|
||||
);
|
||||
}
|
||||
if (!readLimiter.take(result.device.id)) throw new ApiError('rate_limited', 'Too many requests.');
|
||||
return result.device;
|
||||
}
|
||||
|
||||
function requireVersion(value: unknown): void {
|
||||
if (value !== SCHEMA_VERSION && value !== String(SCHEMA_VERSION)) {
|
||||
throw new ApiError('unsupported_schema_version', `This bridge speaks contract version ${SCHEMA_VERSION}.`);
|
||||
}
|
||||
}
|
||||
|
||||
function requireUuid(value: string): string {
|
||||
if (!UUID_RE.test(value)) throw new ApiError('not_found', 'Not found.');
|
||||
return value;
|
||||
}
|
||||
|
||||
function credential(device: DeviceRow, token: string): DeviceCredential {
|
||||
return {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
device_id: device.id,
|
||||
token,
|
||||
token_expires_at: iso(device.token_expires_at),
|
||||
pairing_expires_at: iso(device.pairing_expires_at),
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ health
|
||||
// Liveness only: no configuration, versions, counts or downstream state.
|
||||
app.get('/healthz', async () => ({ status: 'ok', schema_version: SCHEMA_VERSION }));
|
||||
|
||||
// ----------------------------------------------------------------- pairing
|
||||
app.post('/v1/pairing/claim', async (req, reply) => {
|
||||
if (!pairingLimiter.take(req.ip)) throw new ApiError('rate_limited', 'Too many pairing attempts. Wait a minute.');
|
||||
const body = req.body as Record<string, unknown> | undefined;
|
||||
requireVersion(body?.schema_version);
|
||||
if (!check(PairingClaimRequest, body)) throw new ApiError('invalid_request', 'Malformed pairing request.');
|
||||
const result = devices.claimPairingCode(body.code, body.device_name.trim() || 'device');
|
||||
if (!result.ok) {
|
||||
req.log.warn({ reason: result.reason }, 'pairing.rejected');
|
||||
throw new ApiError(
|
||||
result.reason,
|
||||
result.reason === 'pairing_locked'
|
||||
? 'Too many wrong codes. Generate a new pairing code on the bridge.'
|
||||
: 'Pairing code is not valid.',
|
||||
);
|
||||
}
|
||||
req.log.info({ device_id: result.device.id }, 'pairing.claimed');
|
||||
return reply.code(201).send(credential(result.device, result.token));
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ device
|
||||
app.get('/v1/device', async (req): Promise<DeviceStatusResponse> => {
|
||||
const device = authenticate(req);
|
||||
return {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
device_id: device.id,
|
||||
device_name: device.name,
|
||||
token_expires_at: iso(device.token_expires_at),
|
||||
pairing_expires_at: iso(device.pairing_expires_at),
|
||||
agent_reachable: await deps.hermes.reachable(),
|
||||
stt_configured: deps.stt.configured,
|
||||
active_conversation_id: engine.activeConversation(device.id)?.id ?? null,
|
||||
limits: effectiveLimits(config),
|
||||
audio_format: {
|
||||
encoding: AUDIO_FORMAT.encoding,
|
||||
sample_rate: AUDIO_FORMAT.sampleRate,
|
||||
channels: AUDIO_FORMAT.channels,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
app.post('/v1/device/renew', async (req) => {
|
||||
const device = authenticate(req);
|
||||
const renewed = devices.renew(device.id);
|
||||
req.log.info({ device_id: device.id }, 'device.renewed');
|
||||
return credential(renewed.device, renewed.token);
|
||||
});
|
||||
|
||||
app.delete('/v1/device', async (req) => {
|
||||
const device = authenticate(req);
|
||||
devices.revoke(device.id);
|
||||
req.log.info({ device_id: device.id }, 'device.revoked');
|
||||
return { schema_version: SCHEMA_VERSION, revoked: true };
|
||||
});
|
||||
|
||||
// ----------------------------------------------------------- conversations
|
||||
app.post('/v1/conversations', async (req, reply): Promise<ConversationResponse> => {
|
||||
const device = authenticate(req);
|
||||
const body = req.body as Record<string, unknown> | undefined;
|
||||
requireVersion(body?.schema_version);
|
||||
if (!check(ConversationCreateRequest, body)) throw new ApiError('invalid_request', 'Malformed conversation request.');
|
||||
const conversation = engine.createConversation(device.id);
|
||||
reply.code(201);
|
||||
return { schema_version: SCHEMA_VERSION, conversation_id: conversation.id, created_at: iso(conversation.created_at) };
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------- turns
|
||||
app.post('/v1/turns', async (req: FastifyRequest, reply: FastifyReply) => {
|
||||
const device = authenticate(req);
|
||||
const contentType = String(req.headers['content-type'] ?? '').split(';')[0]!.trim().toLowerCase();
|
||||
|
||||
let meta: { requestId: string; conversationId: string; locale: string };
|
||||
let input: { kind: 'text'; text: string } | { kind: 'audio'; pcm: Buffer };
|
||||
|
||||
if (contentType === 'application/json') {
|
||||
const body = req.body as Record<string, unknown> | undefined;
|
||||
requireVersion(body?.schema_version);
|
||||
if (!check(TextTurnRequest, body)) throw new ApiError('invalid_request', 'Malformed turn request.');
|
||||
const text = body.input.text.trim();
|
||||
if (!text) throw new ApiError('invalid_request', 'Text is empty.');
|
||||
meta = { requestId: body.request_id, conversationId: body.conversation_id, locale: body.locale };
|
||||
input = { kind: 'text', text };
|
||||
} else if (contentType === 'application/octet-stream') {
|
||||
const query = req.query as Record<string, unknown>;
|
||||
requireVersion(query.schema_version);
|
||||
if (!check(AudioTurnQuery, query)) {
|
||||
// A declared format we have not validated against real SDK output is refused, not guessed.
|
||||
const formatDeclared = 'encoding' in query || 'sample_rate' in query || 'channels' in query;
|
||||
const formatOk =
|
||||
query.encoding === AUDIO_FORMAT.encoding &&
|
||||
query.sample_rate === String(AUDIO_FORMAT.sampleRate) &&
|
||||
query.channels === String(AUDIO_FORMAT.channels);
|
||||
if (formatDeclared && !formatOk) throw new ApiError('unsupported_media', 'Unsupported audio format.');
|
||||
throw new ApiError('invalid_request', 'Malformed turn metadata.');
|
||||
}
|
||||
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.');
|
||||
meta = { requestId: query.request_id, conversationId: query.conversation_id, locale: query.locale };
|
||||
input = { kind: 'audio', pcm };
|
||||
} else {
|
||||
throw new ApiError('unsupported_media', 'Unsupported content type.');
|
||||
}
|
||||
|
||||
// A duplicate of an existing request never consumes rate budget or creates work.
|
||||
const existing = engine.get(device.id, meta.requestId);
|
||||
if (!existing && !turnLimiter.take(device.id)) throw new ApiError('rate_limited', 'Too many requests. Wait a moment.');
|
||||
|
||||
const result = engine.submit(device.id, meta, input);
|
||||
if (!result.ok) throw new ApiError(result.code, result.message);
|
||||
reply.code(result.replayed ? 200 : 202);
|
||||
return engine.toResult(result.turn, result.replayed);
|
||||
});
|
||||
|
||||
app.get('/v1/turns/:requestId', async (req) => {
|
||||
const device = authenticate(req);
|
||||
const { requestId } = req.params as { requestId: string };
|
||||
// Another device's turn is "not found", never "forbidden": ids are not an oracle.
|
||||
const turn = engine.get(device.id, requireUuid(requestId));
|
||||
if (!turn) throw new ApiError('not_found', 'Not found.');
|
||||
return engine.toResult(turn);
|
||||
});
|
||||
|
||||
app.post('/v1/turns/:requestId/cancel', async (req) => {
|
||||
const device = authenticate(req);
|
||||
const { requestId } = req.params as { requestId: string };
|
||||
const turn = engine.cancel(device.id, requireUuid(requestId));
|
||||
if (!turn) throw new ApiError('not_found', 'Not found.');
|
||||
return engine.toResult(turn);
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { AUDIO_FORMAT } from '@hermeven/contracts';
|
||||
|
||||
export interface TranscribeRequest {
|
||||
/** Raw PCM, signed 16-bit little-endian, mono, 16 kHz. Held in memory only. */
|
||||
pcm: Buffer;
|
||||
locale: string;
|
||||
signal: AbortSignal;
|
||||
}
|
||||
|
||||
export type SttFailureKind = 'unavailable' | 'failed';
|
||||
|
||||
export class SttError extends Error {
|
||||
override name = 'SttError';
|
||||
constructor(
|
||||
readonly kind: SttFailureKind,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export interface SttAdapter {
|
||||
readonly configured: boolean;
|
||||
transcribe(request: TranscribeRequest): Promise<string>;
|
||||
}
|
||||
|
||||
/** Used when no provider is configured: audio turns fail cleanly, typed text still works. */
|
||||
export class NoSttAdapter implements SttAdapter {
|
||||
readonly configured = false;
|
||||
async transcribe(): Promise<string> {
|
||||
throw new SttError('unavailable', 'No speech-to-text provider is configured');
|
||||
}
|
||||
}
|
||||
|
||||
/** Wrap raw PCM in a 44-byte RIFF/WAVE header, in memory. Nothing is written to disk. */
|
||||
export function pcmToWav(pcm: Buffer): Buffer {
|
||||
const header = Buffer.alloc(44);
|
||||
const { sampleRate, channels } = AUDIO_FORMAT;
|
||||
const bytesPerSample = 2;
|
||||
header.write('RIFF', 0, 'ascii');
|
||||
header.writeUInt32LE(36 + pcm.length, 4);
|
||||
header.write('WAVE', 8, 'ascii');
|
||||
header.write('fmt ', 12, 'ascii');
|
||||
header.writeUInt32LE(16, 16);
|
||||
header.writeUInt16LE(1, 20); // PCM
|
||||
header.writeUInt16LE(channels, 22);
|
||||
header.writeUInt32LE(sampleRate, 24);
|
||||
header.writeUInt32LE(sampleRate * channels * bytesPerSample, 28);
|
||||
header.writeUInt16LE(channels * bytesPerSample, 32);
|
||||
header.writeUInt16LE(16, 34);
|
||||
header.write('data', 36, 'ascii');
|
||||
header.writeUInt32LE(pcm.length, 40);
|
||||
return Buffer.concat([header, pcm]);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { pcmToWav, SttError, type SttAdapter, type TranscribeRequest } from './adapter.ts';
|
||||
|
||||
/**
|
||||
* Speech-to-text through any server that implements the OpenAI
|
||||
* `POST {base}/audio/transcriptions` multipart contract (OpenAI, Groq, and
|
||||
* self-hosted Whisper servers such as speaches or whisper.cpp's server). The
|
||||
* operator chooses the endpoint, so audio can stay on hardware they control.
|
||||
*
|
||||
* NOT YET EXERCISED AGAINST A REAL PROVIDER: see docs/feasibility.md.
|
||||
*/
|
||||
export class OpenAiCompatibleStt implements SttAdapter {
|
||||
readonly configured = true;
|
||||
|
||||
constructor(
|
||||
private readonly opts: { baseUrl: string; apiKey: string; model: string; fetchImpl?: typeof fetch },
|
||||
) {}
|
||||
|
||||
async transcribe(request: TranscribeRequest): Promise<string> {
|
||||
const form = new FormData();
|
||||
form.append('file', new Blob([new Uint8Array(pcmToWav(request.pcm))], { type: 'audio/wav' }), 'capture.wav');
|
||||
form.append('model', this.opts.model);
|
||||
form.append('response_format', 'json');
|
||||
const language = request.locale.split('-')[0]?.toLowerCase();
|
||||
if (language) form.append('language', language);
|
||||
|
||||
const headers: Record<string, string> = { Accept: 'application/json' };
|
||||
if (this.opts.apiKey) headers.Authorization = `Bearer ${this.opts.apiKey}`;
|
||||
|
||||
let res: Response;
|
||||
try {
|
||||
res = await (this.opts.fetchImpl ?? fetch)(`${this.opts.baseUrl}/audio/transcriptions`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: form,
|
||||
signal: request.signal,
|
||||
});
|
||||
} catch (err) {
|
||||
if (request.signal.aborted) throw err;
|
||||
throw new SttError('unavailable', 'Speech-to-text provider could not be reached');
|
||||
}
|
||||
if (!res.ok) {
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
throw new SttError(res.status >= 500 || res.status === 429 ? 'unavailable' : 'failed', `Speech-to-text provider answered ${res.status}`);
|
||||
}
|
||||
let json: unknown;
|
||||
try {
|
||||
json = await res.json();
|
||||
} catch {
|
||||
throw new SttError('failed', 'Speech-to-text provider returned an unreadable answer');
|
||||
}
|
||||
const text = (json as { text?: unknown })?.text;
|
||||
if (typeof text !== 'string') throw new SttError('failed', 'Speech-to-text provider returned no text');
|
||||
return text.trim();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user