import { randomUUID } from 'node:crypto'; import { mkdtempSync, rmSync } from 'node:fs'; import type { AddressInfo } from 'node:net'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { Writable } from 'node:stream'; import { pino } from 'pino'; import { SCHEMA_VERSION, type DeviceCredential, type TurnResult } from '@hermeven/contracts'; import { LOG_REDACT, createBridge, type Bridge } from '../../services/bridge/src/app.ts'; import { loadConfig, type BridgeConfig } from '../../services/bridge/src/config.ts'; import type { EngineTiming } from '../../services/bridge/src/turns.ts'; import { FakeHermes } from '../fakes/fakeHermes.ts'; import { FakeStt } from '../fakes/fakeStt.ts'; export const FAST: EngineTiming = { transcribeDeadlineMs: 400, agentDeadlineMs: 900, approvalWaitMs: 500, cancelGraceMs: 400, pollIntervalMs: 20, submitRetryMs: 30, notSentAttempts: 3, }; export interface Harness { hermes: FakeHermes; stt: FakeStt; bridge: Bridge; config: BridgeConfig; url: string; /** Every log line the bridge wrote, for redaction assertions. */ logs: string[]; dir: string; pair(name?: string): Promise; api(method: string, path: string, opts?: { token?: string; json?: unknown; body?: Buffer; headers?: Record }): Promise<{ status: number; body: any; headers: Headers }>; conversation(token: string): Promise; textTurn(token: string, conversationId: string, text: string, requestId?: string): Promise<{ status: number; body: any }>; audioTurn(token: string, conversationId: string, pcm: Buffer, requestId?: string, query?: Record): Promise<{ status: number; body: any }>; waitTerminal(token: string, requestId: string, timeoutMs?: number): Promise; waitState(token: string, requestId: string, state: string, timeoutMs?: number): Promise; /** Stop the bridge process-equivalent and start a new one on the same database. */ restartBridge(): Promise; close(): Promise; } export async function createHarness( opts: { env?: Record; timing?: Partial; stt?: boolean } = {}, ): Promise { const hermes = new FakeHermes(); const stt = new FakeStt(); await hermes.start(); await stt.start(); const dir = mkdtempSync(join(tmpdir(), 'hermeven-test-')); const logs: string[] = []; const sink = new Writable({ write(chunk, _enc, cb) { logs.push(String(chunk)); cb(); }, }); const env: Record = { HERMEVEN_HOST: '127.0.0.1', HERMEVEN_PORT: '0', HERMEVEN_DB_PATH: join(dir, 'bridge.sqlite'), HERMES_BASE_URL: hermes.url, HERMES_API_KEY: hermes.apiKey, HERMEVEN_ALLOWED_ORIGINS: 'https://app.example', HERMES_REQUEST_TIMEOUT_MS: '300', ...(opts.stt === false ? {} : { STT_PROVIDER: 'openai-compatible', STT_BASE_URL: stt.url, STT_API_KEY: stt.apiKey, STT_MODEL: 'fake-whisper' }), ...opts.env, }; const config = loadConfig(env); const timing = { ...FAST, ...opts.timing }; const h = {} as Harness; const boot = async () => { h.bridge = await createBridge(config, { timing, logger: pino({ level: 'debug', redact: { paths: LOG_REDACT, censor: '[redacted]' } }, sink), }); await h.bridge.app.listen({ host: '127.0.0.1', port: 0 }); h.url = `http://127.0.0.1:${(h.bridge.app.server.address() as AddressInfo).port}`; }; Object.assign(h, { hermes, stt, config, logs, dir }); await boot(); h.api = async (method, path, o = {}) => { const headers: Record = { ...(o.headers ?? {}) }; if (o.token) headers.Authorization = `Bearer ${o.token}`; let body: BodyInit | undefined; if (o.json !== undefined) { headers['Content-Type'] = 'application/json'; body = JSON.stringify(o.json); } else if (o.body) { headers['Content-Type'] ??= 'application/octet-stream'; body = new Uint8Array(o.body); } const res = await fetch(`${h.url}${path}`, { method, headers, body }); const text = await res.text(); let parsed: unknown = text; try { parsed = JSON.parse(text); } catch { /* keep raw text */ } return { status: res.status, body: parsed, headers: res.headers }; }; h.pair = async (name = 'test-g2') => { const { code } = h.bridge.devices.createPairingCode(); const res = await h.api('POST', '/v1/pairing/claim', { json: { schema_version: SCHEMA_VERSION, code, device_name: name } }); if (res.status !== 201) throw new Error(`pairing failed: ${res.status} ${JSON.stringify(res.body)}`); return res.body as DeviceCredential; }; h.conversation = async (token) => { const res = await h.api('POST', '/v1/conversations', { token, json: { schema_version: SCHEMA_VERSION } }); if (res.status !== 201) throw new Error(`conversation failed: ${res.status} ${JSON.stringify(res.body)}`); return res.body.conversation_id as string; }; h.textTurn = (token, conversationId, text, requestId = randomUUID()) => h.api('POST', '/v1/turns', { token, json: { schema_version: SCHEMA_VERSION, request_id: requestId, conversation_id: conversationId, locale: 'en-US', input: { kind: 'text', text }, }, }); h.audioTurn = (token, conversationId, pcm, requestId = randomUUID(), query = {}) => { const q = new URLSearchParams({ schema_version: String(SCHEMA_VERSION), request_id: requestId, conversation_id: conversationId, locale: 'en-US', input_kind: 'audio', encoding: 'pcm_s16le', sample_rate: '16000', channels: '1', ...query, }); return h.api('POST', `/v1/turns?${q}`, { token, body: pcm }); }; const waitFor = async (token: string, requestId: string, done: (t: TurnResult) => boolean, timeoutMs: number) => { const deadline = Date.now() + timeoutMs; let last: TurnResult | undefined; while (Date.now() < deadline) { const res = await h.api('GET', `/v1/turns/${requestId}`, { token }); if (res.status === 200) { last = res.body as TurnResult; if (done(last)) return last; } await new Promise((r) => setTimeout(r, 15)); } throw new Error(`timed out waiting for turn ${requestId}; last=${JSON.stringify(last)}`); }; h.waitTerminal = (token, requestId, timeoutMs = 5000) => waitFor(token, requestId, (t) => t.terminal, timeoutMs); h.waitState = (token, requestId, state, timeoutMs = 5000) => waitFor(token, requestId, (t) => t.state === state, timeoutMs); h.restartBridge = async () => { await h.bridge.close(); await boot(); }; h.close = async () => { await h.bridge.close().catch(() => undefined); await hermes.stop(); await stt.stop(); rmSync(dir, { recursive: true, force: true }); }; return h; }