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,298 @@
|
||||
import { execFileSync, spawn, type ChildProcess } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { createServer } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { SCHEMA_VERSION, type TurnResult } from '@hermeven/contracts';
|
||||
import { createBridge, type Bridge } from '../../services/bridge/src/app.ts';
|
||||
import { loadConfig, type BridgeConfig } from '../../services/bridge/src/config.ts';
|
||||
import { StubLlm } from '../fakes/stubLlm.ts';
|
||||
|
||||
/**
|
||||
* REAL HERMES, STUB MODEL.
|
||||
*
|
||||
* The bridge (real code, real HTTP adapter) talks to a real `hermes gateway`
|
||||
* process: the installed hermes-agent, started in a throwaway HERMES_HOME so
|
||||
* the operator's own profile, sessions and credentials are never read or
|
||||
* written. The only fake is the language model behind Hermes (tests/fakes/
|
||||
* stubLlm.ts), which costs nothing and answers deterministically.
|
||||
*
|
||||
* So this verifies Hermeven against Hermes's actual API server behaviour
|
||||
* (admission, idempotency, session continuity, stop). It does not verify a
|
||||
* real model, real tools, a deployed Hermes, or any hardware.
|
||||
*/
|
||||
const API_KEY = `test-${randomUUID()}`;
|
||||
let home: string;
|
||||
let gateway: ChildProcess;
|
||||
let gatewayLog = '';
|
||||
let hermesUrl: string;
|
||||
let llm: StubLlm;
|
||||
let bridge: Bridge;
|
||||
let config: BridgeConfig;
|
||||
let token: string;
|
||||
let hermesVersion = '';
|
||||
|
||||
async function freePort(): Promise<number> {
|
||||
return new Promise((resolve) => {
|
||||
const srv = createServer();
|
||||
srv.listen(0, '127.0.0.1', () => {
|
||||
const { port } = srv.address() as { port: number };
|
||||
srv.close(() => resolve(port));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function startBridge(): Promise<void> {
|
||||
bridge = await createBridge(config);
|
||||
}
|
||||
|
||||
async function api(method: string, path: string, json?: unknown, auth = token) {
|
||||
const res = await bridge.app.inject({
|
||||
method: method as 'GET',
|
||||
url: path,
|
||||
headers: { authorization: `Bearer ${auth}`, ...(json !== undefined ? { 'content-type': 'application/json' } : {}) },
|
||||
payload: json !== undefined ? JSON.stringify(json) : undefined,
|
||||
});
|
||||
return { status: res.statusCode, body: res.json() };
|
||||
}
|
||||
|
||||
async function ask(conversationId: string, text: string, requestId = randomUUID()) {
|
||||
return api('POST', '/v1/turns', {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
request_id: requestId,
|
||||
conversation_id: conversationId,
|
||||
locale: 'en-US',
|
||||
input: { kind: 'text', text },
|
||||
});
|
||||
}
|
||||
|
||||
async function settle(requestId: string, timeoutMs = 60_000): Promise<TurnResult> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
for (;;) {
|
||||
const res = await api('GET', `/v1/turns/${requestId}`);
|
||||
if (res.body.terminal) return res.body as TurnResult;
|
||||
if (Date.now() > deadline) throw new Error(`turn did not settle: ${JSON.stringify(res.body)}\n${gatewayLog.slice(-1500)}`);
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
}
|
||||
|
||||
async function newConversation(): Promise<string> {
|
||||
return (await api('POST', '/v1/conversations', { schema_version: SCHEMA_VERSION })).body.conversation_id;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
hermesVersion = execFileSync('hermes', ['--version'], { encoding: 'utf8' }).split('\n')[0]!.trim();
|
||||
llm = new StubLlm();
|
||||
await llm.start();
|
||||
|
||||
home = mkdtempSync(join(tmpdir(), 'hermeven-hermes-home-'));
|
||||
writeFileSync(
|
||||
join(home, 'config.yaml'),
|
||||
['model:', ' default: "stub-model"', ' provider: "custom"', ` base_url: "${llm.url}"`, ' api_key: "stub-key-not-a-secret"', ''].join('\n'),
|
||||
);
|
||||
const port = await freePort();
|
||||
hermesUrl = `http://127.0.0.1:${port}`;
|
||||
gateway = spawn('hermes', ['gateway', 'run'], {
|
||||
cwd: home,
|
||||
env: {
|
||||
...process.env,
|
||||
HERMES_HOME: home,
|
||||
API_SERVER_ENABLED: 'true',
|
||||
API_SERVER_KEY: API_KEY,
|
||||
API_SERVER_PORT: String(port),
|
||||
API_SERVER_HOST: '127.0.0.1',
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
gateway.stdout!.on('data', (d) => (gatewayLog += String(d)));
|
||||
gateway.stderr!.on('data', (d) => (gatewayLog += String(d)));
|
||||
|
||||
const deadline = Date.now() + 200_000;
|
||||
for (;;) {
|
||||
try {
|
||||
if ((await fetch(`${hermesUrl}/health`)).ok) break;
|
||||
} catch {
|
||||
/* starting */
|
||||
}
|
||||
if (gateway.exitCode !== null) throw new Error(`hermes gateway exited early:\n${gatewayLog.slice(-3000)}`);
|
||||
if (Date.now() > deadline) throw new Error(`hermes gateway did not become healthy:\n${gatewayLog.slice(-3000)}`);
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
}
|
||||
|
||||
config = loadConfig({
|
||||
HERMEVEN_DB_PATH: join(home, 'hermeven-bridge.sqlite'),
|
||||
HERMES_BASE_URL: hermesUrl,
|
||||
HERMES_API_KEY: API_KEY,
|
||||
HERMES_POLL_INTERVAL_MS: '100',
|
||||
HERMEVEN_AGENT_DEADLINE_SECONDS: '60',
|
||||
HERMEVEN_CANCEL_GRACE_SECONDS: '30',
|
||||
});
|
||||
await startBridge();
|
||||
const { code } = bridge.devices.createPairingCode();
|
||||
const claim = await bridge.app.inject({
|
||||
method: 'POST',
|
||||
url: '/v1/pairing/claim',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
payload: JSON.stringify({ schema_version: SCHEMA_VERSION, code, device_name: 'real-hermes-test' }),
|
||||
});
|
||||
token = claim.json().token;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await bridge?.close().catch(() => undefined);
|
||||
try {
|
||||
execFileSync('hermes', ['gateway', 'stop'], { env: { ...process.env, HERMES_HOME: home }, cwd: home, timeout: 60_000, stdio: 'ignore' });
|
||||
} catch {
|
||||
gateway?.kill('SIGTERM');
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
if (gateway && gateway.exitCode === null) gateway.kill('SIGKILL');
|
||||
await llm?.stop();
|
||||
if (home) rmSync(home, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('bridge against a real Hermes gateway (stub model)', () => {
|
||||
it('records which Hermes was tested', async () => {
|
||||
const health = await (await fetch(`${hermesUrl}/health`)).json();
|
||||
console.info(`[real-hermes] CLI: ${hermesVersion}; /health: ${JSON.stringify(health)}`);
|
||||
expect(health.status).toBe('ok');
|
||||
const caps = await (await fetch(`${hermesUrl}/v1/capabilities`, { headers: { Authorization: `Bearer ${API_KEY}` } })).json();
|
||||
expect(caps.features.run_submission).toBe(true);
|
||||
expect(caps.features.run_status).toBe(true);
|
||||
expect(caps.features.run_stop).toBe(true);
|
||||
expect(caps.features.runs_idempotency).toMatchObject({ supported: true, durable: true });
|
||||
console.info(`[real-hermes] runs_idempotency: ${JSON.stringify(caps.features.runs_idempotency)}`);
|
||||
});
|
||||
|
||||
it('device status reports the agent as reachable', async () => {
|
||||
expect((await api('GET', '/v1/device')).body.agent_reachable).toBe(true);
|
||||
});
|
||||
|
||||
it('a typed question is answered through Hermes, with Hermeven instructions layered on', async () => {
|
||||
const conv = await newConversation();
|
||||
const res = await ask(conv, 'My favourite colour is teal.');
|
||||
expect(res.status).toBe(202);
|
||||
const done = await settle(res.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.answer_text).toContain('STUB-ANSWER users=1');
|
||||
expect(done.answer_text).toContain('My favourite colour is teal.');
|
||||
// The per-request instructions reached the model's system prompt, alongside Hermes' own.
|
||||
expect(llm.lastSystem).toContain('heads-up display');
|
||||
console.info(`[real-hermes] first turn agent_ms=${done.timings.agent_ms}`);
|
||||
});
|
||||
|
||||
it('a follow-up carries the earlier turn through Hermes’ own session store; a new conversation does not', async () => {
|
||||
const conv = await newConversation();
|
||||
await settle((await ask(conv, 'Remember the word pineapple.')).body.request_id);
|
||||
const followUp = await settle((await ask(conv, 'What word did I ask you to remember?')).body.request_id);
|
||||
expect(followUp.outcome).toBe('succeeded');
|
||||
// The model was handed both user turns by Hermes; the bridge sent only the new one.
|
||||
expect(llm.lastUserMessages).toEqual(['Remember the word pineapple.', 'What word did I ask you to remember?']);
|
||||
expect(followUp.answer_text).toContain('users=2');
|
||||
|
||||
const fresh = await newConversation();
|
||||
const first = await settle((await ask(fresh, 'What word did I ask you to remember?')).body.request_id);
|
||||
expect(first.answer_text).toContain('users=1');
|
||||
expect(llm.lastUserMessages).toEqual(['What word did I ask you to remember?']);
|
||||
});
|
||||
|
||||
it('duplicate submits reach the model exactly once (backend invocation counter)', async () => {
|
||||
const conv = await newConversation();
|
||||
const before = llm.calls;
|
||||
const id = randomUUID();
|
||||
const results = await Promise.all(Array.from({ length: 6 }, () => ask(conv, 'Count me once.', id)));
|
||||
expect(results.filter((r) => r.status === 202)).toHaveLength(1);
|
||||
expect(results.filter((r) => r.status === 200 && r.body.replayed)).toHaveLength(5);
|
||||
await settle(id);
|
||||
await ask(conv, 'Count me once.', id);
|
||||
expect(llm.calls - before).toBe(1);
|
||||
});
|
||||
|
||||
it('Hermes replays an identical keyed submit and refuses a changed one (the adapter’s premise)', async () => {
|
||||
const key = `hermeven-test-${randomUUID()}`;
|
||||
const body = JSON.stringify({ input: 'idempotency probe', session_id: `hermeven-${randomUUID()}` });
|
||||
const post = (payload: string) =>
|
||||
fetch(`${hermesUrl}/v1/runs`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': key },
|
||||
body: payload,
|
||||
});
|
||||
const before = llm.calls;
|
||||
const first = await post(body);
|
||||
expect(first.status).toBe(202);
|
||||
const runId = (await first.json()).run_id;
|
||||
const again = await post(body);
|
||||
expect(again.status).toBe(202);
|
||||
expect(again.headers.get('idempotency-replayed')).toBe('true');
|
||||
expect((await again.json()).run_id).toBe(runId);
|
||||
const changed = await post(JSON.stringify({ input: 'something else', session_id: 'x' }));
|
||||
expect(changed.status).toBe(409);
|
||||
expect((await changed.json()).error.code).toBe('idempotency_key_conflict');
|
||||
await new Promise((r) => setTimeout(r, 3000));
|
||||
expect(llm.calls - before).toBe(1);
|
||||
});
|
||||
|
||||
it('cancel during a slow turn: Hermes confirms the stop and no answer is delivered', async () => {
|
||||
const conv = await newConversation();
|
||||
llm.delayMs = 15_000;
|
||||
try {
|
||||
const res = await ask(conv, 'This will take a while.');
|
||||
const id = res.body.request_id;
|
||||
const deadline = Date.now() + 20_000;
|
||||
while ((await api('GET', `/v1/turns/${id}`)).body.state !== 'thinking') {
|
||||
if (Date.now() > deadline) throw new Error('never reached thinking');
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
const started = Date.now();
|
||||
const cancel = await api('POST', `/v1/turns/${id}/cancel`, {});
|
||||
expect(cancel.body.cancel_requested).toBe(true);
|
||||
const done = await settle(id, 45_000);
|
||||
console.info(`[real-hermes] cancel settled as ${done.outcome} in ${Date.now() - started} ms`);
|
||||
expect(done.outcome).toBe('cancelled');
|
||||
expect(done.answer_text).toBeNull();
|
||||
} finally {
|
||||
llm.delayMs = 0;
|
||||
}
|
||||
});
|
||||
|
||||
it('a bridge restart mid-turn re-attaches to the same Hermes run', async () => {
|
||||
const conv = await newConversation();
|
||||
llm.delayMs = 4000;
|
||||
try {
|
||||
const before = llm.calls;
|
||||
const res = await ask(conv, 'Survive a restart.');
|
||||
const id = res.body.request_id;
|
||||
await new Promise((r) => setTimeout(r, 1200));
|
||||
await bridge.close();
|
||||
await startBridge();
|
||||
const done = await settle(id, 60_000);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.answer_text).toContain('Survive a restart.');
|
||||
expect(llm.calls - before).toBe(1);
|
||||
} finally {
|
||||
llm.delayMs = 0;
|
||||
}
|
||||
});
|
||||
|
||||
it('a wrong Hermes key is a definite rejection: nothing runs', async () => {
|
||||
await bridge.close();
|
||||
const good = config;
|
||||
config = { ...good, hermes: { ...good.hermes, apiKey: 'wrong-key' } };
|
||||
await startBridge();
|
||||
try {
|
||||
const conv = await newConversation();
|
||||
const before = llm.calls;
|
||||
const done = await settle((await ask(conv, 'Should not run.')).body.request_id);
|
||||
expect(done.outcome).toBe('failed');
|
||||
expect(done.error?.code).toBe('agent_rejected');
|
||||
expect(llm.calls).toBe(before);
|
||||
} finally {
|
||||
await bridge.close();
|
||||
config = good;
|
||||
await startBridge();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user