Files
Kelx/services/server-agent-provider-http.js
T
2026-11-30 16:32:37 +00:00

62 lines
2.1 KiB
JavaScript

"use strict";
const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
class AiProviderError extends Error {
constructor(message, { status, failureCode, responseData, cause } = {}) {
super(message || "AI request failed.", { cause });
this.name = "AiProviderError";
this.status = status;
this.failureCode = failureCode;
this.responseData = responseData;
}
}
function responseTooLarge() {
return new AiProviderError("AI provider response is too large", { failureCode: "agent_provider_response_too_large" });
}
async function proxyAiRequest(url, options, timeoutMs = 60000) {
// adpanel:agent-provider-budget - headers, body and decompressed bytes share one bounded exchange.
const timeoutSignal = AbortSignal.timeout(timeoutMs);
const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
try {
const response = await fetch(url, {
method: options.method || "POST",
headers: options.headers,
body: options.body,
redirect: "manual",
signal,
});
if (Number(response.headers.get("content-length")) > MAX_RESPONSE_BYTES) {
await response.body?.cancel();
throw responseTooLarge();
}
const chunks = [];
let size = 0;
if (response.body) {
for await (const chunk of response.body) {
size += chunk.byteLength;
if (size > MAX_RESPONSE_BYTES) throw responseTooLarge();
chunks.push(chunk);
}
}
signal.throwIfAborted();
const raw = Buffer.concat(chunks, size).toString("utf8");
let data;
try {
data = JSON.parse(raw);
} catch {
data = { raw };
}
return { status: response.status, data, headers: Object.fromEntries(response.headers) };
} catch (error) {
options.signal?.throwIfAborted();
if (timeoutSignal.aborted) throw new AiProviderError("Request timeout", { failureCode: "agent_provider_timeout", cause: error });
if (error instanceof AiProviderError) throw error;
throw new AiProviderError("Could not connect to the AI provider", { failureCode: "agent_provider_unreachable", cause: error });
}
}
module.exports = { AiProviderError, proxyAiRequest };