import * as plugins from './plugins.js'; const bodylessMethods: ReadonlySet = new Set(['GET', 'HEAD']); const toRequest = (incomingArg: plugins.http.IncomingMessage, signalArg: AbortSignal): Request => { const headers = new Headers(); for (let index = 0; index + 1 < incomingArg.rawHeaders.length; index += 2) { headers.append(incomingArg.rawHeaders[index], incomingArg.rawHeaders[index + 1]); } const method = incomingArg.method ?? 'GET'; // Only the path and query are taken from the request line; the Host header stays a header, for the // service's `authenticate` to judge. const url = new URL(incomingArg.url ?? '/', 'http://localhost'); return new Request(url, { method, headers, signal: signalArg, ...(bodylessMethods.has(method) ? {} // `Readable.toWeb` is typed with Node's own stream/web types, which the global `BodyInit` does not name. : { body: plugins.Readable.toWeb(incomingArg) as ReadableStream, duplex: 'half' as const }), }); }; /** * Writes the service's answer to `requestArg` into `outgoingArg`. The write follows the request's own signal and holds * the request until it settles: Node's fetch stops a request's signal from following the signal it was built with once * the request is collected, and the service may keep only the signal, so a request dropped mid-answer would never * learn that its client left. */ const writeResponse = async ( requestArg: Request, responseArg: Response, outgoingArg: plugins.http.ServerResponse, ): Promise => { if (requestArg.signal.aborted) { // The client left while the answer was prepared; cancelling the body releases what it holds, such as the // model call and the ping timer of a stream. await responseArg.body?.cancel(requestArg.signal.reason); return; } outgoingArg.writeHead(responseArg.status, Object.fromEntries(responseArg.headers)); outgoingArg.flushHeaders(); if (!responseArg.body) { outgoingArg.end(); return; } const reader = responseArg.body.getReader(); const onAbort = (): void => { void reader.cancel(requestArg.signal.reason).catch(() => undefined); }; requestArg.signal.addEventListener('abort', onAbort, { once: true }); let finished = false; try { while (!requestArg.signal.aborted) { const { done, value } = await reader.read(); if (done) { finished = true; break; } // A socket that closes while full aborts the signal, which ends this wait. if (!outgoingArg.write(value)) await plugins.once(outgoingArg, 'drain', { signal: requestArg.signal }); } } finally { requestArg.signal.removeEventListener('abort', onAbort); // A write that failed leaves the body unread; cancelling it releases the model call and the ping timer. if (!finished) await reader.cancel(requestArg.signal.reason).catch(() => undefined); reader.releaseLock(); } if (!requestArg.signal.aborted) outgoingArg.end(); }; /** * Hosts an Anthropic Messages service on a Node HTTP server: `http.createServer(listener)`. * * A streamed answer is written as it is produced and waits for the socket when it is full. A client that * disconnects aborts its request, which stops the model call behind it. */ export const createAnthropicMessagesNodeListener = ( serviceArg: plugins.IAnthropicMessagesService, ): ((incomingArg: plugins.http.IncomingMessage, outgoingArg: plugins.http.ServerResponse) => void) => ( incomingArg, outgoingArg, ) => { const abort = new AbortController(); outgoingArg.once('close', () => { if (!outgoingArg.writableFinished) abort.abort(new Error('The client closed the connection.')); }); void (async () => { const request = toRequest(incomingArg, abort.signal); await writeResponse(request, await serviceArg.handle(request), outgoingArg); })().catch((errorArg: unknown) => { // A client that left has no one to tell; its abort already ended the answer. if (abort.signal.aborted) return; if (!outgoingArg.headersSent) { outgoingArg.writeHead(500, { 'content-type': 'application/json' }); outgoingArg.end(JSON.stringify({ type: 'error', error: { type: 'api_error', message: `The request could not be served: ${errorArg instanceof Error ? errorArg.message : String(errorArg)}` }, })); return; } outgoingArg.destroy(errorArg instanceof Error ? errorArg : new Error(String(errorArg))); }); };