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 { 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((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 { const server = this.server; this.server = null; if (server) { server.closeAllConnections(); await new Promise((resolve) => server.close(() => resolve())); } } }