Files
hermeven/tests/fakes/fakeHermes.ts
DanandClaude Fable 5.2 4687cc0114 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>
2026-11-18 18:21:49 -08:00

259 lines
9.9 KiB
TypeScript

import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import type { AddressInfo } from 'node:net';
/**
* TEST FAKE. Not Hermes.
*
* A deterministic stand-in for the Hermes API server's Runs API, written from
* the hermes-agent v0.23.1 source (gateway/platforms/api_server_runs.py). It
* exists so the bridge's real HTTP adapter can be exercised against scripted
* outcomes and faults. A passing test against this file is evidence about
* Hermeven's logic only, never about Hermes or about hardware.
*/
export interface FakeRun {
runId: string;
key: string;
body: string;
sessionId: string;
input: string;
status: string;
output: string;
extra: Record<string, unknown>;
stopRequested: boolean;
timer: ReturnType<typeof setTimeout> | null;
}
export type Script =
| { kind: 'complete'; afterMs?: number; output?: string }
| { kind: 'fail'; afterMs?: number; error?: string }
| { kind: 'incomplete'; afterMs?: number; output: string }
| { kind: 'approval' }
| { kind: 'hang' }
| { kind: 'unknown'; afterMs?: number }
| { kind: 'interrupted'; afterMs?: number };
export class FakeHermes {
readonly apiKey = 'fake-hermes-key';
/** How many turns actually "executed". The duplicate-execution counter. */
executions = 0;
readonly runs = new Map<string, FakeRun>();
private readonly byKey = new Map<string, FakeRun>();
/** session id -> inputs seen, to prove follow-ups land in the same session. */
readonly sessions = new Map<string, string[]>();
readonly requests: Array<{ method: string; path: string; idempotencyKey?: string }> = [];
private script: Script[] = [];
private defaultScript: Script = { kind: 'complete' };
/** Faults applied to upcoming POST /v1/runs calls, in order. */
private submitFaults: Array<'drop_response' | 'http_503' | 'http_500' | 'http_400'> = [];
/** When true, every request is refused at the socket level. */
private server: Server | null = null;
private stopIgnored = false;
private statusDown = false;
private seq = 0;
url = '';
async start(port = 0): Promise<void> {
this.server = createServer((req, res) => void this.handle(req, res));
await new Promise<void>((resolve) => this.server!.listen(port, '127.0.0.1', resolve));
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
}
get port(): number {
return Number(new URL(this.url).port);
}
async stop(): Promise<void> {
for (const run of this.runs.values()) if (run.timer) clearTimeout(run.timer);
const server = this.server;
this.server = null;
if (server) {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
}
next(...scripts: Script[]): void {
this.script.push(...scripts);
}
setDefault(script: Script): void {
this.defaultScript = script;
}
failNextSubmit(...faults: Array<'drop_response' | 'http_503' | 'http_500' | 'http_400'>): void {
this.submitFaults.push(...faults);
}
ignoreStop(value = true): void {
this.stopIgnored = value;
}
setStatusDown(value: boolean): void {
this.statusDown = value;
}
/** Resolve a pending approval the way another, verified surface would. */
approve(runId: string, output = 'approved and done'): void {
const run = this.runs.get(runId)!;
run.status = 'running';
this.finishLater(run, { kind: 'complete', afterMs: 30, output });
}
/** Forget every run, as if status retention had expired. */
forgetRuns(): void {
this.runs.clear();
}
lastRun(): FakeRun | undefined {
return [...this.runs.values()].at(-1);
}
private json(res: ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}): void {
res.writeHead(status, { 'Content-Type': 'application/json', ...headers });
res.end(JSON.stringify(body));
}
private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
const url = new URL(req.url ?? '/', 'http://x');
const path = url.pathname;
const key = req.headers['idempotency-key'];
this.requests.push({ method: req.method ?? '', path, idempotencyKey: typeof key === 'string' ? key : undefined });
if (path === '/health') return this.json(res, 200, { status: 'ok' });
if (req.headers.authorization !== `Bearer ${this.apiKey}`) {
return this.json(res, 401, { error: { message: 'Invalid API key', code: 'invalid_api_key' } });
}
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
const raw = Buffer.concat(chunks).toString('utf8');
if (req.method === 'POST' && path === '/v1/runs') return this.submit(req, res, raw);
const match = /^\/v1\/runs\/([^/]+)(\/stop)?$/.exec(path);
if (match) {
const run = this.runs.get(decodeURIComponent(match[1]!));
if (req.method === 'GET' && !match[2]) {
if (this.statusDown) return this.json(res, 503, { error: { message: 'storage_unavailable' } });
if (!run) return this.json(res, 404, { error: { message: 'Run not found', code: 'run_not_found' } });
return this.json(res, 200, {
object: 'hermes.run',
run_id: run.runId,
status: run.status,
session_id: run.sessionId,
...(run.output ? { output: run.output } : {}),
...run.extra,
});
}
if (req.method === 'POST' && match[2]) {
if (!run) return this.json(res, 404, { error: { message: 'Run not found', code: 'run_not_found' } });
if (['completed', 'failed', 'cancelled', 'interrupted'].includes(run.status)) {
return this.json(res, 200, { run_id: run.runId, status: run.status });
}
if (!this.stopIgnored) {
run.stopRequested = true;
run.status = 'stopping';
if (run.timer) clearTimeout(run.timer);
run.timer = setTimeout(() => {
run.status = 'cancelled';
run.extra = { completed: false, partial: false, interrupted: true };
}, 25);
}
return this.json(res, 200, { run_id: run.runId, status: 'stopping' });
}
}
this.json(res, 404, { error: { message: 'not found' } });
}
private submit(req: IncomingMessage, res: ServerResponse, raw: string): void {
const key = String(req.headers['idempotency-key'] ?? '');
const fault = this.submitFaults.shift();
if (fault === 'http_503') return this.json(res, 503, { error: { message: 'runtime_draining' } }, { 'Retry-After': '1' });
if (fault === 'http_400') return this.json(res, 400, { error: { message: "Missing 'input' field" } });
let body: { input?: string; session_id?: string; instructions?: string };
try {
body = JSON.parse(raw);
} catch {
return this.json(res, 400, { error: { message: 'Invalid JSON' } });
}
if (!body.input) return this.json(res, 400, { error: { message: "Missing 'input' field" } });
const existing = key ? this.byKey.get(key) : undefined;
let run: FakeRun;
let replayed = false;
if (existing) {
if (existing.body !== raw) {
return this.json(res, 409, {
error: { message: 'Idempotency-Key was already used with a different request payload', code: 'idempotency_key_conflict' },
});
}
run = existing;
replayed = true;
} else {
const sessionId = body.session_id || `run-session-${this.seq}`;
run = {
runId: `run_${String(++this.seq).padStart(6, '0')}`,
key,
body: raw,
sessionId,
input: body.input,
status: 'running',
output: '',
extra: {},
stopRequested: false,
timer: null,
};
this.runs.set(run.runId, run);
if (key) this.byKey.set(key, run);
// The turn "executes" exactly once, at admission.
this.executions += 1;
const history = this.sessions.get(sessionId) ?? [];
this.sessions.set(sessionId, history);
const script = this.script.shift() ?? this.defaultScript;
const defaultOutput = `FAKE-ANSWER turn=${history.length + 1} previous=${JSON.stringify(history.at(-1) ?? null)} input=${JSON.stringify(body.input)}`;
history.push(body.input);
this.finishLater(run, script, defaultOutput);
}
// Admitted, but the answer never reaches the caller.
if (fault === 'drop_response') return void res.destroy();
if (fault === 'http_500') return this.json(res, 500, { error: { message: 'boom' } });
this.json(res, 202, { run_id: run.runId, status: replayed ? run.status : 'started', replayed }, replayed ? { 'Idempotency-Replayed': 'true' } : {});
}
private finishLater(run: FakeRun, script: Script, defaultOutput = ''): void {
const settle = (fn: () => void, afterMs = 30) => {
run.timer = setTimeout(() => {
if (!run.stopRequested) fn();
}, afterMs);
};
switch (script.kind) {
case 'complete':
return settle(() => {
run.status = 'completed';
run.output = script.output ?? defaultOutput;
run.extra = { completed: true, partial: false, interrupted: false };
}, script.afterMs);
case 'fail':
return settle(() => {
run.status = 'failed';
run.extra = { completed: false, partial: false, interrupted: false, error: script.error ?? 'agent run failed' };
}, script.afterMs);
case 'incomplete':
return settle(() => {
run.status = 'failed';
run.output = script.output;
run.extra = { completed: false, partial: true, interrupted: false, turn_exit_reason: 'max_iterations' };
}, script.afterMs);
case 'approval':
run.status = 'waiting_for_approval';
return;
case 'unknown':
return settle(() => {
run.status = 'unknown';
}, script.afterMs);
case 'interrupted':
return settle(() => {
run.status = 'interrupted';
run.extra = { error: 'Gateway shutdown interrupted the run.' };
}, script.afterMs);
case 'hang':
return;
}
}
}