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,86 @@
|
||||
import type { HudFrame } from '../../apps/even-client/src/core/hud.ts';
|
||||
import type { DeviceEvent } from '../../apps/even-client/src/device/events.ts';
|
||||
import type { DevicePort } from '../../apps/even-client/src/device/port.ts';
|
||||
|
||||
/**
|
||||
* TEST FAKE. Not glasses, not the simulator.
|
||||
*
|
||||
* Records what the app would draw, and lets a test play gestures and audio
|
||||
* frames. It proves the app's logic against the DevicePort contract only.
|
||||
*/
|
||||
export class FakeDevice implements DevicePort {
|
||||
frames: HudFrame[] = [];
|
||||
micOpen = false;
|
||||
micOpens = 0;
|
||||
micCloses = 0;
|
||||
micAllowed = true;
|
||||
exitRequests = 0;
|
||||
readonly storage = new Map<string, string>();
|
||||
private readonly listeners = new Set<(event: DeviceEvent) => void>();
|
||||
private readonly connectionListeners = new Set<(connected: boolean) => void>();
|
||||
|
||||
get frame(): HudFrame {
|
||||
return this.frames.at(-1) ?? { body: '', status: '' };
|
||||
}
|
||||
|
||||
async init(frame: HudFrame): Promise<boolean> {
|
||||
this.frames.push(frame);
|
||||
return true;
|
||||
}
|
||||
show(frame: HudFrame): void {
|
||||
this.frames.push(frame);
|
||||
}
|
||||
async startMic(): Promise<boolean> {
|
||||
if (!this.micAllowed) return false;
|
||||
this.micOpen = true;
|
||||
this.micOpens += 1;
|
||||
return true;
|
||||
}
|
||||
async stopMic(): Promise<void> {
|
||||
if (this.micOpen) this.micCloses += 1;
|
||||
this.micOpen = false;
|
||||
}
|
||||
onEvent(listener: (event: DeviceEvent) => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
onConnection(listener: (connected: boolean) => void): () => void {
|
||||
this.connectionListeners.add(listener);
|
||||
return () => this.connectionListeners.delete(listener);
|
||||
}
|
||||
async requestExit(): Promise<void> {
|
||||
this.exitRequests += 1;
|
||||
}
|
||||
async storageGet(key: string): Promise<string> {
|
||||
return this.storage.get(key) ?? '';
|
||||
}
|
||||
async storageSet(key: string, value: string): Promise<void> {
|
||||
this.storage.set(key, value);
|
||||
}
|
||||
|
||||
// ---- test controls
|
||||
emit(event: DeviceEvent): void {
|
||||
for (const l of this.listeners) l(event);
|
||||
}
|
||||
tap = () => this.emit({ type: 'tap' });
|
||||
doubleTap = () => this.emit({ type: 'double_tap' });
|
||||
swipeDown = () => this.emit({ type: 'swipe_down' });
|
||||
swipeUp = () => this.emit({ type: 'swipe_up' });
|
||||
menu = (itemId: number) => this.emit({ type: 'menu', itemId });
|
||||
connection(connected: boolean): void {
|
||||
for (const l of this.connectionListeners) l(connected);
|
||||
}
|
||||
/** Deliver audio the way the SDK documents it: 100 ms frames of 3,200 bytes. Only while the mic is open. */
|
||||
speak(seconds: number): void {
|
||||
const frames = Math.round(seconds * 10);
|
||||
for (let i = 0; i < frames && this.micOpen; i++) {
|
||||
const pcm = new Uint8Array(3200);
|
||||
for (let s = 0; s < 1600; s++) {
|
||||
const v = Math.round(Math.sin((2 * Math.PI * 440 * (i * 1600 + s)) / 16000) * 8000);
|
||||
pcm[s * 2] = v & 0xff;
|
||||
pcm[s * 2 + 1] = (v >> 8) & 0xff;
|
||||
}
|
||||
this.emit({ type: 'audio', pcm });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { createServer, type Server } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
|
||||
/**
|
||||
* TEST FAKE. Not a speech recogniser.
|
||||
*
|
||||
* Accepts the OpenAI-style `POST /audio/transcriptions` multipart upload,
|
||||
* checks that what arrived really is a 16 kHz mono 16-bit WAV, and returns a
|
||||
* scripted transcript. It proves the bridge's upload format and failure
|
||||
* handling, and nothing about real transcription quality or latency.
|
||||
*/
|
||||
export class FakeStt {
|
||||
readonly apiKey = 'fake-stt-key';
|
||||
calls = 0;
|
||||
lastWav: { sampleRate: number; channels: number; bitsPerSample: number; dataBytes: number } | null = null;
|
||||
lastFields: Record<string, string> = {};
|
||||
private replies: Array<{ text?: string; status?: number; delayMs?: number }> = [];
|
||||
private server: Server | null = null;
|
||||
url = '';
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.server = createServer(async (req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) chunks.push(chunk as Buffer);
|
||||
const body = Buffer.concat(chunks);
|
||||
if (req.method !== 'POST' || !req.url?.endsWith('/audio/transcriptions')) {
|
||||
res.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
if (req.headers.authorization !== `Bearer ${this.apiKey}`) {
|
||||
res.writeHead(401, { 'Content-Type': 'application/json' }).end('{"error":"unauthorized"}');
|
||||
return;
|
||||
}
|
||||
this.calls += 1;
|
||||
const riff = body.indexOf('RIFF');
|
||||
if (riff >= 0 && body.toString('ascii', riff + 8, riff + 12) === 'WAVE') {
|
||||
this.lastWav = {
|
||||
channels: body.readUInt16LE(riff + 22),
|
||||
sampleRate: body.readUInt32LE(riff + 24),
|
||||
bitsPerSample: body.readUInt16LE(riff + 34),
|
||||
dataBytes: body.readUInt32LE(riff + 40),
|
||||
};
|
||||
} else {
|
||||
this.lastWav = null;
|
||||
}
|
||||
const text = body.toString('latin1');
|
||||
this.lastFields = {};
|
||||
for (const m of text.matchAll(/name="(model|language|response_format)"\r\n\r\n([^\r]*)\r\n/g)) {
|
||||
this.lastFields[m[1]!] = m[2]!;
|
||||
}
|
||||
const reply = this.replies.shift() ?? { text: 'what is the capital of france' };
|
||||
if (reply.delayMs) await new Promise((r) => setTimeout(r, reply.delayMs));
|
||||
if (res.destroyed) return;
|
||||
if (reply.status && reply.status !== 200) {
|
||||
res.writeHead(reply.status, { 'Content-Type': 'application/json' }).end('{"error":"scripted failure"}');
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ text: reply.text ?? '' }));
|
||||
});
|
||||
await new Promise<void>((resolve) => this.server!.listen(0, '127.0.0.1', resolve));
|
||||
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
|
||||
}
|
||||
|
||||
next(...replies: Array<{ text?: string; status?: number; delayMs?: number }>): void {
|
||||
this.replies.push(...replies);
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
const server = this.server;
|
||||
this.server = null;
|
||||
if (server) {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Deterministic synthetic PCM (a sine tone). Stands in for speech in tests; it is not speech. */
|
||||
export function syntheticPcm(seconds: number, sampleRate = 16000): Buffer {
|
||||
const samples = Math.floor(seconds * sampleRate);
|
||||
const buf = Buffer.alloc(samples * 2);
|
||||
for (let i = 0; i < samples; i++) buf.writeInt16LE(Math.round(Math.sin((2 * Math.PI * 440 * i) / sampleRate) * 8000), i * 2);
|
||||
return buf;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { createServer, type Server } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
|
||||
/**
|
||||
* TEST STUB. Not a language model.
|
||||
*
|
||||
* A minimal OpenAI-compatible chat endpoint so a REAL Hermes gateway can run
|
||||
* whole agent turns without any provider account or cost. Its "answer" is a
|
||||
* deterministic description of the conversation it was handed, which is how
|
||||
* the real-Hermes test proves that Hermes itself carried the earlier turns.
|
||||
*/
|
||||
export class StubLlm {
|
||||
/** Agent turns served. */
|
||||
calls = 0;
|
||||
auxiliaryCalls = 0;
|
||||
delayMs = 0;
|
||||
/** User messages seen in the most recent request, oldest first. */
|
||||
lastUserMessages: string[] = [];
|
||||
lastSystem = '';
|
||||
private server: Server | null = null;
|
||||
url = '';
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.server = createServer(async (req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) chunks.push(chunk as Buffer);
|
||||
const path = (req.url ?? '').split('?')[0]!;
|
||||
if (req.method === 'GET' && path.endsWith('/models')) {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({ object: 'list', data: [{ id: 'stub-model', object: 'model', owned_by: 'hermeven-test' }] }));
|
||||
return;
|
||||
}
|
||||
if (req.method !== 'POST' || !path.endsWith('/chat/completions')) {
|
||||
res.writeHead(404, { 'Content-Type': 'application/json' }).end('{"error":{"message":"not found"}}');
|
||||
return;
|
||||
}
|
||||
let body: { messages?: Array<{ role: string; content: unknown }>; stream?: boolean; model?: string };
|
||||
try {
|
||||
body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
||||
} catch {
|
||||
res.writeHead(400).end('{}');
|
||||
return;
|
||||
}
|
||||
const text = (c: unknown): string =>
|
||||
typeof c === 'string' ? c : Array.isArray(c) ? c.map((p) => (p && typeof p === 'object' && 'text' in p ? String((p as { text: unknown }).text) : '')).join('') : '';
|
||||
const messages = body.messages ?? [];
|
||||
const users = messages.filter((m) => m.role === 'user').map((m) => text(m.content));
|
||||
// Hermes also calls the model for housekeeping (naming the chat, compressing history).
|
||||
// Those are not agent turns and must not be counted as executions.
|
||||
const system = text(messages.find((m) => m.role === 'system')?.content).slice(0, 600);
|
||||
const isTurn = users.length > 0 && !/you name chat sessions|generate a (short )?title|summari[sz]e/i.test(system);
|
||||
if (!isTurn) this.auxiliaryCalls += 1;
|
||||
if (isTurn) {
|
||||
this.calls += 1;
|
||||
this.lastUserMessages = users;
|
||||
this.lastSystem = messages.filter((m) => m.role === 'system').map((m) => text(m.content)).join('\n');
|
||||
}
|
||||
const answer = `STUB-ANSWER users=${users.length} first=${JSON.stringify(users[0] ?? null)} last=${JSON.stringify(users.at(-1) ?? null)}`;
|
||||
if (this.delayMs) await new Promise((r) => setTimeout(r, this.delayMs));
|
||||
if (res.destroyed) return;
|
||||
const id = `chatcmpl-stub-${this.calls}`;
|
||||
const created = Math.floor(Date.now() / 1000);
|
||||
const usage = { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 };
|
||||
if (body.stream) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
|
||||
const chunk = (delta: object, finish: string | null, extra: object = {}) =>
|
||||
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model: body.model ?? 'stub-model', choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`);
|
||||
chunk({ role: 'assistant', content: '' }, null);
|
||||
chunk({ content: answer }, null);
|
||||
chunk({}, 'stop', { usage });
|
||||
res.end('data: [DONE]\n\n');
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
id,
|
||||
object: 'chat.completion',
|
||||
created,
|
||||
model: body.model ?? 'stub-model',
|
||||
choices: [{ index: 0, message: { role: 'assistant', content: answer }, finish_reason: 'stop' }],
|
||||
usage,
|
||||
}),
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve) => this.server!.listen(0, '127.0.0.1', resolve));
|
||||
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}/v1`;
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
const server = this.server;
|
||||
this.server = null;
|
||||
if (server) {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user