Spaces:
Runtime error
Runtime error
File size: 12,091 Bytes
cd8bd0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | import { getPendingById } from "@/lib/usage/usageHistory";
import { sanitizeErrorMessage } from "./error.ts";
type JsonRecord = Record<string, unknown>;
type HeaderInput =
| Headers
| Record<string, unknown>
| { entries?: () => IterableIterator<[string, string]> }
| null
| undefined;
export type RequestPipelinePayloads = {
clientRawRequest?: JsonRecord;
openaiRequest?: JsonRecord;
providerRequest?: JsonRecord;
providerResponse?: JsonRecord;
clientResponse?: JsonRecord;
error?: JsonRecord;
streamChunks?: {
provider?: string[];
openai?: string[];
client?: string[];
};
};
type RequestLogger = {
sessionPath: null;
logClientRawRequest: (endpoint: unknown, body: unknown, headers?: HeaderInput) => void;
logOpenAIRequest: (body: unknown) => void;
logTargetRequest: (url: unknown, headers: HeaderInput, body: unknown) => void;
logProviderResponse: (
status: unknown,
statusText: unknown,
headers: HeaderInput,
body: unknown
) => void;
appendProviderChunk: (chunk: string) => void;
appendOpenAIChunk: (chunk: string) => void;
logConvertedResponse: (body: unknown) => void;
appendConvertedChunk: (chunk: string) => void;
logError: (error: unknown, requestBody?: unknown) => void;
getPipelinePayloads: () => RequestPipelinePayloads | null;
};
type RequestLoggerOptions = {
enabled?: boolean;
captureStreamChunks?: boolean;
maxStreamChunkBytes?: number;
maxStreamChunkItems?: number;
requestId?: string | null;
model?: string;
provider?: string;
connectionId?: string | null;
};
const DEFAULT_MAX_STREAM_CHUNK_BYTES = 128 * 1024;
const DEFAULT_MAX_STREAM_CHUNK_ITEMS = 10_240;
const MAX_LOG_STRING_LENGTH = 64 * 1024;
export const MAX_LOG_ARRAY_ITEMS = 24;
const MAX_LOG_OBJECT_KEYS = 80;
function maskSensitiveHeaders(headers: HeaderInput): Record<string, unknown> {
if (!headers) return {};
const headerEntries =
typeof (headers as Headers).entries === "function"
? Object.fromEntries((headers as Headers).entries())
: { ...(headers as Record<string, unknown>) };
const masked = { ...headerEntries };
const sensitiveKeys = ["authorization", "x-api-key", "cookie", "token"];
for (const key of Object.keys(masked)) {
const lowerKey = key.toLowerCase();
// Whitelist x-ratelimit- headers from redaction
if (lowerKey.startsWith("x-ratelimit-")) {
continue;
}
if (!sensitiveKeys.some((candidate) => lowerKey.includes(candidate))) {
continue;
}
const value = masked[key];
if (typeof value === "string" && value.length > 20) {
masked[key] = `${value.slice(0, 10)}...${value.slice(-5)}`;
} else if (value) {
masked[key] = "[REDACTED]";
}
}
return masked;
}
function createEmptyStreamChunks() {
return {
provider: [] as string[],
openai: [] as string[],
client: [] as string[],
};
}
function truncateLogString(value: string, maxLength = MAX_LOG_STRING_LENGTH): string {
if (value.length <= maxLength) return value;
return `${value.slice(0, Math.floor(maxLength / 2))}\n[...truncated ${value.length - maxLength} chars...]\n${value.slice(-Math.ceil(maxLength / 2))}`;
}
/**
* Recursively clone `value` for logging, with size bounds applied:
* - Arrays longer than MAX_LOG_ARRAY_ITEMS are truncated to the tail with a
* sentinel marker prepended.
* - The `tools` field is exempt from array truncation: the full tool inventory
* is debug-critical for understanding which tools the model had access to,
* and individual tool descriptions are independently bounded by
* truncateLogString, so the total size remains naturally capped.
*
* The optional `key` parameter carries the parent object's field name when
* recursing into an object's values, enabling the per-field exemption above.
* Top-level arrays (no key context) remain subject to truncation.
*/
export function cloneBoundedForLog(value: unknown, depth = 0, key: string | null = null): unknown {
if (value === null || value === undefined) return value;
if (typeof value === "string") return truncateLogString(value);
if (typeof value !== "object") return value;
if (depth >= 6) return "[MaxDepth]";
if (Array.isArray(value)) {
const exempt = key === "tools";
const shouldTruncate = !exempt && value.length > MAX_LOG_ARRAY_ITEMS;
const source = shouldTruncate ? value.slice(-MAX_LOG_ARRAY_ITEMS) : value;
const mapped = source.map((item) => cloneBoundedForLog(item, depth + 1));
if (shouldTruncate) {
return [
{
_omniroute_truncated_array: true,
originalLength: value.length,
retainedTailItems: MAX_LOG_ARRAY_ITEMS,
},
...mapped,
];
}
return mapped;
}
const result: JsonRecord = {};
const entries = Object.entries(value as JsonRecord);
for (const [k, item] of entries.slice(0, MAX_LOG_OBJECT_KEYS)) {
result[k] = cloneBoundedForLog(item, depth + 1, k);
}
if (entries.length > MAX_LOG_OBJECT_KEYS) {
result._omniroute_truncated_keys = entries.length - MAX_LOG_OBJECT_KEYS;
}
return result;
}
function appendBoundedChunk(
chunks: string[],
bytes: { value: number; truncated: boolean },
chunk: string,
maxBytes: number,
maxItems = DEFAULT_MAX_STREAM_CHUNK_ITEMS
) {
if (typeof chunk !== "string" || chunk.length === 0) {
return;
}
if (chunks.length >= maxItems) {
bytes.truncated = true;
chunks[maxItems - 1] = `[stream chunk log truncated after ${maxItems} chunks]`;
return;
}
if (bytes.value >= maxBytes) {
bytes.truncated = true;
return;
}
const remaining = maxBytes - bytes.value;
if (chunk.length <= remaining) {
chunks.push(chunk);
bytes.value += chunk.length;
return;
}
chunks.push(chunk.slice(0, remaining));
if (chunks.length < maxItems) {
chunks.push(`[stream chunk log truncated after ${maxBytes} bytes]`);
}
bytes.value = maxBytes;
bytes.truncated = true;
}
function hasOwnValues(value: unknown): boolean {
return Boolean(value && typeof value === "object" && Object.keys(value as JsonRecord).length > 0);
}
function compactPipelinePayloads(
payloads: RequestPipelinePayloads
): RequestPipelinePayloads | null {
const result: RequestPipelinePayloads = {};
for (const [key, value] of Object.entries(payloads)) {
if (value === null || value === undefined) {
continue;
}
if (key === "streamChunks" && value && typeof value === "object") {
const chunkRecord = value as Record<string, unknown>;
const compactedChunks = Object.fromEntries(
Object.entries(chunkRecord).filter(
([, chunkValue]) => Array.isArray(chunkValue) && chunkValue.length > 0
)
);
if (Object.keys(compactedChunks).length > 0) {
result.streamChunks = compactedChunks;
}
continue;
}
result[key as keyof RequestPipelinePayloads] = value;
}
return hasOwnValues(result) ? result : null;
}
function makeStreamChunkMethods(options: RequestLoggerOptions, captureChunks: boolean) {
const streamChunks = createEmptyStreamChunks();
const streamChunkBytes = {
provider: { value: 0, truncated: false },
openai: { value: 0, truncated: false },
client: { value: 0, truncated: false },
};
const maxBytes =
Number.isInteger(options.maxStreamChunkBytes) && Number(options.maxStreamChunkBytes) > 0
? Number(options.maxStreamChunkBytes)
: DEFAULT_MAX_STREAM_CHUNK_BYTES;
const maxItems =
Number.isInteger(options.maxStreamChunkItems) && Number(options.maxStreamChunkItems) > 0
? Number(options.maxStreamChunkItems)
: DEFAULT_MAX_STREAM_CHUNK_ITEMS;
let pendingPushed = false;
const push = () => {
if (pendingPushed) return;
if (!options.requestId && (!options.connectionId || !options.model)) return;
pendingPushed = true;
try {
const pending = getPendingById();
const exactEntry = options.requestId ? pending.get(options.requestId) : null;
if (exactEntry) {
exactEntry.streamChunks = { ...streamChunks };
return;
}
for (const entry of pending.values()) {
if (
entry?.connectionId === options.connectionId &&
entry?.model === options.model &&
entry?.provider === (options.provider || "")
) {
entry.streamChunks = { ...streamChunks };
return;
}
}
} catch (e) {
// Do not allow logging failures to disrupt request handling
try {
console.warn("[requestLogger] updatePendingRequestStreamChunks failed:", e);
} catch {}
}
};
const append = (arr: string[], bytes: { value: number; truncated: boolean }, chunk: string) => {
if (!captureChunks) return;
push();
appendBoundedChunk(arr, bytes, chunk, maxBytes, maxItems);
};
return {
streamChunks,
streamChunkBytes,
appendProviderChunk(chunk: string) {
append(streamChunks.provider, streamChunkBytes.provider, chunk);
},
appendOpenAIChunk(chunk: string) {
append(streamChunks.openai, streamChunkBytes.openai, chunk);
},
appendConvertedChunk(chunk: string) {
append(streamChunks.client, streamChunkBytes.client, chunk);
},
};
}
export async function createRequestLogger(
_sourceFormat?: string,
_targetFormat?: string,
_model?: string,
options: RequestLoggerOptions = {}
): Promise<RequestLogger> {
const captureStreamChunks = options.captureStreamChunks !== false;
// Stream chunk capture is always set up — even when the logger is disabled,
// so that active requests always have real-time stream data available via
// the /api/logs/active endpoint.
const chunkMethods = makeStreamChunkMethods(options, captureStreamChunks);
if (options.enabled === false) {
return {
sessionPath: null,
logClientRawRequest() {},
logOpenAIRequest() {},
logTargetRequest() {},
logProviderResponse() {},
appendProviderChunk: chunkMethods.appendProviderChunk,
appendOpenAIChunk: chunkMethods.appendOpenAIChunk,
logConvertedResponse() {},
appendConvertedChunk: chunkMethods.appendConvertedChunk,
logError() {},
getPipelinePayloads() {
return null;
},
};
}
const payloads: RequestPipelinePayloads = {
...(captureStreamChunks ? { streamChunks: chunkMethods.streamChunks } : {}),
};
return {
sessionPath: null,
logClientRawRequest(endpoint, body, headers = {}) {
payloads.clientRawRequest = {
timestamp: new Date().toISOString(),
endpoint,
headers: maskSensitiveHeaders(headers),
body: cloneBoundedForLog(body),
};
},
logOpenAIRequest(body) {
payloads.openaiRequest = {
timestamp: new Date().toISOString(),
body: cloneBoundedForLog(body),
};
},
logTargetRequest(url, headers, body) {
payloads.providerRequest = {
timestamp: new Date().toISOString(),
url,
headers: maskSensitiveHeaders(headers),
body: cloneBoundedForLog(body),
};
},
logProviderResponse(status, statusText, headers, body) {
payloads.providerResponse = {
timestamp: new Date().toISOString(),
status,
statusText,
headers: maskSensitiveHeaders(headers),
body: cloneBoundedForLog(body),
};
},
appendProviderChunk: chunkMethods.appendProviderChunk,
appendOpenAIChunk: chunkMethods.appendOpenAIChunk,
logConvertedResponse(body) {
payloads.clientResponse = {
timestamp: new Date().toISOString(),
body: cloneBoundedForLog(body),
};
},
appendConvertedChunk: chunkMethods.appendConvertedChunk,
logError(error, requestBody = null) {
payloads.error = {
timestamp: new Date().toISOString(),
error: sanitizeErrorMessage(error instanceof Error ? error.message : String(error)),
requestBody: cloneBoundedForLog(requestBody),
};
},
getPipelinePayloads() {
return compactPipelinePayloads(payloads);
},
};
}
|