import type * as plugins from './plugins.js'; import { AnthropicMessagesError, describeFailure, failureBody, failureHeaders, invalidRequest, } from './errors.js'; import type { IAnthropicMessagesFailure, IAnthropicMessagesService, IAnthropicMessagesServiceOptions, TAnthropicMessagesStreamEvent, } from './interfaces.js'; import { createAnthropicMessagesModelCall, parseAnthropicMessagesRequest } from './request.js'; import { ThinkingSignatures } from './signature.js'; import { AnthropicMessagesAccumulator, AnthropicMessagesStreamTranslator, encodeServerSentEvent, } from './stream.js'; const defaultPingIntervalMs = 15_000; const defaultMaxRequestBytes = 32 * 1024 * 1024; const newId = (prefixArg: string): string => `${prefixArg}_${crypto.randomUUID().replace(/-/g, '')}`; const failureResponse = (failureArg: IAnthropicMessagesFailure, requestIdArg: string): Response => new Response( failureBody(failureArg, requestIdArg), { status: failureArg.status, headers: { 'content-type': 'application/json', 'request-id': requestIdArg, ...failureHeaders(failureArg) }, }, ); /** A header value keeps printable ASCII only. */ const headerText = (textArg: string): string => textArg.replace(/[^\x20-\x7e]/g, '?'); const describeWarnings = (warningsArg: readonly plugins.SharedV4Warning[]): string | undefined => { const named = warningsArg.map((warning) => { switch (warning.type) { case 'unsupported': case 'compatibility': return `${warning.type}:${warning.feature}`; case 'deprecated': return `deprecated:${warning.setting}`; default: return warning.type; } }); return named.length > 0 ? headerText(named.join(', ')) : undefined; }; /** Reads a JSON body up to a size limit, refusing a larger one before it is read in full. */ const readJsonBody = async (requestArg: Request, maxBytesArg: number): Promise => { const tooLarge = (): AnthropicMessagesError => new AnthropicMessagesError( 413, 'request_too_large', `The request body exceeds ${maxBytesArg} bytes.`, ); const declared = requestArg.headers.get('content-length'); if (declared !== null && Number(declared) > maxBytesArg) throw tooLarge(); if (!requestArg.body) throw invalidRequest('The request has no body.'); const reader = requestArg.body.getReader(); const chunks: Uint8Array[] = []; let size = 0; try { while (true) { const { done, value } = await reader.read(); if (done) break; size += value.byteLength; if (size > maxBytesArg) throw tooLarge(); chunks.push(value); } } catch (errorArg) { await reader.cancel().catch(() => undefined); throw errorArg; } finally { reader.releaseLock(); } const body = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { body.set(chunk, offset); offset += chunk.byteLength; } try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body)) as unknown; } catch { throw invalidRequest('The request body is not JSON.'); } }; /** * Serves the Anthropic Messages API over FlexHarness models: `POST /v1/messages`, streamed or not, and * `GET /v1/models`. `POST /v1/messages/count_tokens` answers 404, on which an Anthropic client estimates * token counts itself. It works on WHATWG `Request` and `Response`, so any HTTP server can host it; the * `/anthropic-messages/node` subpath hosts it on a Node HTTP server. */ export const createAnthropicMessagesService = ( optionsArg: IAnthropicMessagesServiceOptions, ): IAnthropicMessagesService => { const pingIntervalMs = optionsArg.pingIntervalMs ?? defaultPingIntervalMs; const maxRequestBytes = optionsArg.maxRequestBytes ?? defaultMaxRequestBytes; const signatures = new ThinkingSignatures(optionsArg.signatureKey); const listModels = async (contextArg: TContext, requestIdArg: string): Promise => { const models = await optionsArg.listModels(contextArg); return new Response(JSON.stringify({ data: models.map((model) => ({ type: 'model', id: model.id, ...(model.displayName === undefined ? {} : { display_name: model.displayName }), ...(model.description === undefined ? {} : { description: model.description }), })), has_more: false, first_id: models[0]?.id ?? null, last_id: models.at(-1)?.id ?? null, }), { status: 200, headers: { 'content-type': 'application/json', 'request-id': requestIdArg } }); }; const createMessage = async ( requestArg: Request, contextArg: TContext, requestIdArg: string, ): Promise => { const parsed = parseAnthropicMessagesRequest(await readJsonBody(requestArg, maxRequestBytes)); // A client that leaves before the model call gets none: checked before its model is resolved and before it is called. requestArg.signal.throwIfAborted(); const model = await optionsArg.resolveModel(parsed.modelId, contextArg, requestArg.signal); if (!model) { const served = (await optionsArg.listModels(contextArg)).map((entry) => entry.id); throw new AnthropicMessagesError( 404, 'not_found_error', `model: "${parsed.modelId}" is not served here. Served models: ${served.length > 0 ? served.join(', ') : 'none'}.`, ); } const call = await createAnthropicMessagesModelCall( parsed, model, signatures, requestArg.headers.get('x-claude-code-session-id') ?? undefined, ); requestArg.signal.throwIfAborted(); // The model call stops when the client leaves or when this service ends the answer early. const abort = new AbortController(); const modelSignal = AbortSignal.any([requestArg.signal, abort.signal]); let reader: ReadableStreamDefaultReader; let firstPart: IteratorResult; try { reader = (await model.model.doStream({ ...call.options, abortSignal: modelSignal })).stream.getReader(); firstPart = await reader.read(); } catch (errorArg) { abort.abort(); return failureResponse(describeFailure(errorArg, model), requestIdArg); } const warnings = !firstPart.done && firstPart.value.type === 'stream-start' ? describeWarnings(firstPart.value.warnings) : undefined; const headers: Record = { 'request-id': requestIdArg, ...call.notices, ...(warnings === undefined ? {} : { 'x-flexharness-model-warnings': warnings }), }; const translator = new AnthropicMessagesStreamTranslator({ messageId: newId('msg'), modelId: parsed.modelId, thinking: parsed.thinking, signatures, signatureScope: model.signatureScope, toolNames: call.toolNames, }); let pending: IteratorResult | undefined = firstPart; const nextEvents = async (): Promise => { const part = pending ?? await reader.read(); pending = undefined; if (part.done) { throw new AnthropicMessagesError(500, 'api_error', 'The model stream ended before the message finished.'); } return await translator.push(part.value); }; // Usage is reported once the answer is complete and outside its path, so bookkeeping cannot change it. const reportUsage = (): void => { const reporter = optionsArg.usage; const usage = translator.usage; if (!reporter || !usage) return; const event = { context: contextArg, modelId: parsed.modelId, usage }; void Promise.resolve() .then(() => reporter.record(event)) .catch((errorArg: unknown) => reporter.failed(errorArg, event)); }; const finish = async (): Promise => { await reader.cancel().catch(() => undefined); }; if (!parsed.stream) { const accumulator = new AnthropicMessagesAccumulator(); accumulator.apply(translator.start()); try { while (!translator.isFinished) { for (const event of await nextEvents()) accumulator.apply(event); } } catch (errorArg) { abort.abort(); await finish(); return failureResponse(describeFailure(errorArg, model), requestIdArg); } await finish(); reportUsage(); return new Response(JSON.stringify(accumulator.result()), { status: 200, headers: { ...headers, 'content-type': 'application/json' }, }); } const encoder = new TextEncoder(); let pingTimer: ReturnType | undefined; let lastWrite = Date.now(); let closed = false; const stopPing = (): void => { if (pingTimer !== undefined) clearInterval(pingTimer); pingTimer = undefined; }; const write = (controllerArg: ReadableStreamDefaultController, eventArg: TAnthropicMessagesStreamEvent): void => { controllerArg.enqueue(encoder.encode(encodeServerSentEvent(eventArg))); lastWrite = Date.now(); }; const body = new ReadableStream({ start: (controller) => { write(controller, translator.start()); // An idle stream still shows it is alive: a client aborts a stream that stays silent too long. pingTimer = setInterval(() => { if (!closed && Date.now() - lastWrite >= pingIntervalMs) write(controller, { type: 'ping' }); }, pingIntervalMs); }, pull: async (controller) => { try { // A pull that enqueues nothing is not repeated, so parts that yield no event are read past here. let events: TAnthropicMessagesStreamEvent[] = []; while (events.length === 0 && !translator.isFinished) events = await nextEvents(); for (const event of events) write(controller, event); if (translator.isFinished) { closed = true; stopPing(); await finish(); controller.close(); reportUsage(); } } catch (errorArg) { if (closed) return; closed = true; stopPing(); abort.abort(); const failure = describeFailure(errorArg, model); write(controller, { type: 'error', error: { type: failure.type, message: failure.message } }); await finish(); controller.close(); } }, cancel: async (reasonArg) => { closed = true; stopPing(); abort.abort(reasonArg); await finish(); }, }); return new Response(body, { status: 200, headers: { ...headers, 'content-type': 'text/event-stream', 'cache-control': 'no-cache' }, }); }; const handle = async (requestArg: Request): Promise => { const requestId = newId('req'); try { const path = new URL(requestArg.url).pathname; if (path === '/api/hello' && (requestArg.method === 'HEAD' || requestArg.method === 'GET')) { // The connection-warming probe of an Anthropic client, sent without a credential. return new Response(null, { status: 200, headers: { 'request-id': requestId } }); } const routes: Readonly> = { '/v1/messages': 'POST', '/v1/messages/count_tokens': 'POST', '/v1/models': 'GET', }; const method = routes[path]; if (method === undefined) { throw new AnthropicMessagesError(404, 'not_found_error', `${path} is not served here.`); } if (requestArg.method !== method) { throw new AnthropicMessagesError(405, 'invalid_request_error', `${path} accepts ${method} only.`); } const context = await optionsArg.authenticate(requestArg); if (path === '/v1/models') return await listModels(context, requestId); if (path === '/v1/messages/count_tokens') { throw new AnthropicMessagesError( 404, 'not_found_error', 'Token counting is not served here; the client estimates token counts instead.', ); } return await createMessage(requestArg, context, requestId); } catch (errorArg) { return failureResponse(describeFailure(errorArg), requestId); } }; return { handle }; };