Bridge: an owner-configured list of agents (HERMEVEN_AGENTS). Each extra agent is another profile of the same Hermes gateway, reached at /p/<profile> with that profile's own key. GET /v1/agents lists ids and names; POST /v1/conversations takes an optional agent_id checked against the list. A conversation belongs to one agent (migration v3) and its turns are submitted, polled and stopped at that agent. /v1/device is unchanged so clients built earlier keep working. Client: at Ready a swipe moves between agents; the name is shown through the exchange; each agent keeps its own conversation; a follow-up goes to the agent that answered. Reopened within the conversation window it opens on the last agent, otherwise on the default. With one agent, or a bridge without /v1/agents, nothing changes. Also: contract section G, server survey and key evidence, the 0.1.2 upload, and the CODY-020 correction. Not reviewed, not deployed, not uploaded. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
283 lines
11 KiB
TypeScript
283 lines
11 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;
|
|
/** The profile the run was submitted under (null = default). Invisible from any other. */
|
|
profile: string | null;
|
|
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; profile?: string | null }> = [];
|
|
/** Named profiles served under `/p/<name>`, each with its own key. */
|
|
readonly profiles = new Map<string, string>();
|
|
/** Which profile each executed run belonged to (null = default), in order. */
|
|
readonly executedBy: Array<string | null> = [];
|
|
|
|
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');
|
|
let path = url.pathname;
|
|
// Like a gateway with multiplex_profiles: `/p/<profile>/...` selects a named profile, which
|
|
// has its OWN key; the default's key is refused there, and an unserved profile is a 404.
|
|
let profile: string | null = null;
|
|
let expectedKey = this.apiKey;
|
|
const prefixed = /^\/p\/([^/]+)(\/.*)$/.exec(path);
|
|
if (prefixed) {
|
|
profile = prefixed[1]!;
|
|
path = prefixed[2]!;
|
|
const profileKey = this.profiles.get(profile);
|
|
if (profileKey === undefined) return this.json(res, 404, { error: { message: 'Unknown profile' } });
|
|
expectedKey = profileKey;
|
|
}
|
|
const key = req.headers['idempotency-key'];
|
|
this.requests.push({ method: req.method ?? '', path, idempotencyKey: typeof key === 'string' ? key : undefined, profile });
|
|
|
|
if (path === '/health') return this.json(res, 200, { status: 'ok' });
|
|
if (req.headers.authorization !== `Bearer ${expectedKey}`) {
|
|
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, profile);
|
|
|
|
const match = /^\/v1\/runs\/([^/]+)(\/stop)?$/.exec(path);
|
|
if (match) {
|
|
const found = this.runs.get(decodeURIComponent(match[1]!));
|
|
const run = found && found.profile === profile ? found : undefined;
|
|
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, runProfile: string | null): void {
|
|
// Keys are scoped to the profile, as in Hermes: the same key under another profile is a different run.
|
|
const key = String(req.headers['idempotency-key'] ?? '');
|
|
const scopedKey = key && `${runProfile ?? ''}|${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 = scopedKey ? this.byKey.get(scopedKey) : 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,
|
|
profile: runProfile,
|
|
status: 'running',
|
|
output: '',
|
|
extra: {},
|
|
stopRequested: false,
|
|
timer: null,
|
|
};
|
|
this.runs.set(run.runId, run);
|
|
if (scopedKey) this.byKey.set(scopedKey, run);
|
|
// The turn "executes" exactly once, at admission.
|
|
this.executions += 1;
|
|
this.executedBy.push(runProfile);
|
|
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;
|
|
}
|
|
}
|
|
}
|