// src/lib/http-transport.ts import { startupHttpSpan } from '../../bin/startup-trace.mjs'; import type { ServerRegistry } from './server-registry.js'; import { readTransportResponse, type TransportResponse, } from '../short-command/transport-response.js'; export class ApiError extends Error { constructor( public readonly status: number, public readonly body: string, public readonly method: string, public readonly path: string, public readonly response?: TransportResponse, ) { super(`API error ${status}: ${body}`); this.name = 'ApiError'; } } function parseJsonBody(body: string): any | null { try { return JSON.parse(body); } catch { return null; } } export function formatApiError(err: ApiError): string { if (err.status === 429) { const data = parseJsonBody(err.body); const error = data?.error ?? {}; const code = error?.code ?? data?.code ?? 'RATE_LIMITED'; const retryAfter = error?.retry_after ?? error?.['retry after'] ?? data?.retry_after ?? data?.['retry after']; const hint = error?.hint ?? data?.hint; const message = error?.message ?? data?.message ?? 'Too many requests.'; const retryText = retryAfter !== undefined ? ` Retry after ${retryAfter}s.` : ''; const hintText = hint ? ` Hint: ${hint}.` : ''; return `Rate limited (${code}). ${message}.${retryText}${hintText}`; } return `Request failed (${err.status}): ${err.body}`; } export class HttpTransport { private apiKey: string; private registry: ServerRegistry; private extraHeaders: Record; private signal?: AbortSignal; constructor( apiKey: string, registry: ServerRegistry, extraHeaders: Record = {}, signal?: AbortSignal, ) { this.apiKey = apiKey; this.registry = registry; this.extraHeaders = extraHeaders; this.signal = signal; } /** * Generic HTTP request. Supports JSON body and FormData. * Adds Authorization header when apiKey is non-empty. * `perRequestHeaders` are merged last (highest precedence) so a caller can * attach a header to a single endpoint without polluting every request. */ async requestRaw( method: string, path: string, body?: any, perRequestHeaders?: Record, // A caller may cancel one request without aborting the transport owner. requestSignal?: AbortSignal, ): Promise { const url = this.registry.baseUrlFor(path) + path; const headers: Record = {}; // Only add auth header if apiKey is present (register endpoint has no auth) if (this.apiKey) { headers['Authorization'] = `Bearer ${this.apiKey}`; } for (const [k, v] of Object.entries(this.extraHeaders)) headers[k] = v; if (perRequestHeaders) { for (const [k, v] of Object.entries(perRequestHeaders)) headers[k] = v; } let fetchBody: BodyInit | undefined; if (body !== undefined) { if (body instanceof FormData) { fetchBody = body; // Let fetch set Content-Type with boundary for FormData } else { headers['Content-Type'] = 'application/json; charset=utf-8'; fetchBody = JSON.stringify(body); } } const timeout = AbortSignal.timeout(10_000); const signals = [timeout, this.signal, requestSignal] .filter((value): value is AbortSignal => value !== undefined); const signal = signals.length === 1 ? signals[0] : AbortSignal.any(signals); const stop = startupHttpSpan(method, path); if (!stop) { const res = await fetch(url, { method, headers, body: fetchBody, signal }); return readTransportResponse(res, { method, path }); } let status: number | undefined; try { const res = await fetch(url, { method, headers, body: fetchBody, signal }); status = res.status; const response = await readTransportResponse(res, { method, path }); stop(res.ok ? 'ok' : 'error', status); return response; } catch (error) { stop('error', status); throw error; } } async request( method: string, path: string, body?: any, perRequestHeaders?: Record, requestSignal?: AbortSignal, ): Promise { const response = await this.requestRaw(method, path, body, perRequestHeaders, requestSignal); if (response.status < 200 || response.status >= 300) { throw new ApiError(response.status, response.body.rawText, method, path, response); } if (response.body.kind !== 'json') { // Preserve the legacy promise contract: callers requested JSON and an // empty/non-JSON success is still a protocol error, not a fabricated value. throw new SyntaxError(response.body.kind === 'empty' ? 'Unexpected end of JSON input' : `Unexpected non-JSON response from ${path}`); } return response.body.value as T; } async getRaw(path: string): Promise { try { return await this.requestRaw('GET', path); } catch (err) { await new Promise(r => setTimeout(r, 500)); return this.requestRaw('GET', path); } } async postRaw(path: string, body?: any, perRequestHeaders?: Record, requestSignal?: AbortSignal): Promise { return this.requestRaw('POST', path, body, perRequestHeaders, requestSignal); } /** GET with one fast retry for transient network failures. */ /** GET with optional per-request cancellation in addition to owner cancellation. */ async get(path: string, requestSignal?: AbortSignal): Promise { try { return await this.request('GET', path, undefined, undefined, requestSignal); } catch (err) { // Only retry network errors, not HTTP errors if (err instanceof ApiError) throw err; if (requestSignal?.aborted) throw requestSignal.reason ?? err; await new Promise((resolve) => { const timer = setTimeout(finish, 500); const onAbort = (): void => finish(); function finish(): void { clearTimeout(timer); requestSignal?.removeEventListener('abort', onAbort); resolve(); } requestSignal?.addEventListener('abort', onAbort, { once: true }); }); if (requestSignal?.aborted) throw requestSignal.reason ?? err; return this.request('GET', path, undefined, undefined, requestSignal); } } async post(path: string, body?: any, perRequestHeaders?: Record): Promise { return this.request('POST', path, body, perRequestHeaders); } /** GET raw bytes (binary artifacts). Throws ApiError on non-ok. */ async getBytes(path: string): Promise { const url = this.registry.baseUrlFor(path) + path; const headers: Record = {}; if (this.apiKey) { headers['Authorization'] = `Bearer ${this.apiKey}`; } for (const [k, v] of Object.entries(this.extraHeaders)) headers[k] = v; const res = await fetch(url, { method: 'GET', headers, signal: AbortSignal.timeout(30_000) }); if (!res.ok) { throw new ApiError(res.status, await res.text(), 'GET', path); } return Buffer.from(await res.arrayBuffer()); } }