Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(transport): cap streaming logs and parse fragmented responses (#1647)

diegosouzapw3008ba9a13c8
diff --git a/open-sse/executors/antigravity.ts b/open-sse/executors/antigravity.ts
index 5b9a3ed0d9..166bb38cb9 100644
--- a/open-sse/executors/antigravity.ts
+++ b/open-sse/executors/antigravity.ts
@@ -27,6 +27,13 @@ const CREDITS_EXHAUSTED_TTL_MS = 5 * 60 * 60 * 1000; // 5 hours
const BARE_PRO_IDS = new Set(["gemini-3.1-pro"]);
+type AntigravityCollectedStream = {
+ textContent: string;
+ finishReason: string;
+ usage: Record<string, unknown> | null;
+ remainingCredits: Array<{ creditType: string; creditAmount: string }> | null;
+};
+
/**
* Per-account GOOGLE_ONE_AI credits-exhausted tracker.
* Key: accountId (OAuth subject / email). Value: expiry timestamp.
@@ -91,6 +98,72 @@ function markCreditsExhausted(accountId: string): void {
creditsExhaustedUntil.set(accountId, Date.now() + CREDITS_EXHAUSTED_TTL_MS);
}
+function processAntigravitySSEPayload(
+ payload: string,
+ collected: AntigravityCollectedStream,
+ log?: { debug?: (scope: string, message: string) => void }
+) {
+ if (!payload || payload === "[DONE]") return;
+ try {
+ const parsed = JSON.parse(payload);
+ const candidate = parsed?.response?.candidates?.[0];
+ if (candidate?.content?.parts) {
+ for (const part of candidate.content.parts) {
+ if (typeof part.text === "string" && !part.thought && !part.thoughtSignature) {
+ collected.textContent += part.text;
+ }
+ }
+ }
+ if (candidate?.finishReason) {
+ collected.finishReason =
+ candidate.finishReason.toLowerCase() === "stop"
+ ? "stop"
+ : candidate.finishReason.toLowerCase();
+ }
+ if (parsed?.response?.usageMetadata) {
+ const um = parsed.response.usageMetadata;
+ collected.usage = {
+ prompt_tokens: um.promptTokenCount || 0,
+ completion_tokens: um.candidatesTokenCount || 0,
+ total_tokens: um.totalTokenCount || 0,
+ };
+ }
+ if (Array.isArray(parsed?.remainingCredits)) {
+ collected.remainingCredits = parsed.remainingCredits;
+ }
+ } catch {
+ log?.debug?.("SSE_PARSE", `Skipping malformed SSE line: ${payload.slice(0, 80)}`);
+ }
+}
+
+function processAntigravitySSEText(
+ text: string,
+ partialLine: { value: string },
+ collected: AntigravityCollectedStream,
+ log?: { debug?: (scope: string, message: string) => void }
+) {
+ partialLine.value += text;
+ const lines = partialLine.value.split("\n");
+ partialLine.value = lines.pop() || "";
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed.startsWith("data:")) continue;
+ processAntigravitySSEPayload(trimmed.slice(5).trim(), collected, log);
+ }
+}
+
+function flushAntigravitySSEText(
+ partialLine: { value: string },
+ collected: AntigravityCollectedStream,
+ log?: { debug?: (scope: string, message: string) => void }
+) {
+ const trimmed = partialLine.value.trim();
+ partialLine.value = "";
+ if (!trimmed.startsWith("data:")) return;
+ processAntigravitySSEPayload(trimmed.slice(5).trim(), collected, log);
+}
+
/**
* Strip provider prefixes (e.g. "antigravity/model" → "model").
* Ensures the model name sent to the upstream API never contains a routing prefix.
@@ -367,7 +440,13 @@ export class AntigravityExecutor extends BaseExecutor {
const SSE_COLLECT_TIMEOUT_MS = 120_000;
const collect = async () => {
- const chunks: string[] = [];
+ const collected: AntigravityCollectedStream = {
+ textContent: "",
+ finishReason: "stop",
+ usage: null,
+ remainingCredits: null,
+ };
+ const partialLine = { value: "" };
let timedOut = false;
const timeout = AbortSignal.timeout(SSE_COLLECT_TIMEOUT_MS);
try {
@@ -384,7 +463,12 @@ export class AntigravityExecutor extends BaseExecutor {
),
]);
if (done) break;
- chunks.push(decoder.decode(value, { stream: true }));
+ processAntigravitySSEText(
+ decoder.decode(value, { stream: true }),
+ partialLine,
+ collected,
+ log
+ );
}
} catch (err) {
const msg = err?.message || String(err);
@@ -392,51 +476,8 @@ export class AntigravityExecutor extends BaseExecutor {
log?.warn?.("SSE_COLLECT", `Error collecting SSE stream: ${msg}`);
// Fall through — return whatever was collected so far
}
- const rawSSE = chunks.join("");
-
- // Parse Gemini SSE: each line is "data: {json}"
- let textContent = "";
- let finishReason = "stop";
- let usage: Record<string, unknown> | null = null;
- let remainingCredits: Array<{ creditType: string; creditAmount: string }> | null = null;
- const lines = rawSSE.split("\n");
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed.startsWith("data:")) continue;
- const payload = trimmed.slice(5).trim();
- if (!payload || payload === "[DONE]") continue;
- try {
- const parsed = JSON.parse(payload);
- const candidate = parsed?.response?.candidates?.[0];
- if (candidate?.content?.parts) {
- for (const part of candidate.content.parts) {
- if (typeof part.text === "string" && !part.thought && !part.thoughtSignature) {
- textContent += part.text;
- }
- }
- }
- if (candidate?.finishReason) {
- finishReason =
- candidate.finishReason.toLowerCase() === "stop"
- ? "stop"
- : candidate.finishReason.toLowerCase();
- }
- if (parsed?.response?.usageMetadata) {
- const um = parsed.response.usageMetadata;
- usage = {
- prompt_tokens: um.promptTokenCount || 0,
- completion_tokens: um.candidatesTokenCount || 0,
- total_tokens: um.totalTokenCount || 0,
- };
- }
- // Credit balance — arrives in the final chunk alongside consumedCredits
- if (Array.isArray(parsed?.remainingCredits)) {
- remainingCredits = parsed.remainingCredits;
- }
- } catch (e) {
- log?.debug?.("SSE_PARSE", `Skipping malformed SSE line: ${payload.slice(0, 80)}`);
- }
- }
+ processAntigravitySSEText(decoder.decode(), partialLine, collected, log);
+ flushAntigravitySSEText(partialLine, collected, log);
const result = {
id: `chatcmpl-${Date.now()}-${crypto.randomUUID().slice(0, 8)}`,
@@ -446,13 +487,13 @@ export class AntigravityExecutor extends BaseExecutor {
choices: [
{
index: 0,
- message: { role: "assistant", content: textContent },
- finish_reason: timedOut ? "length" : finishReason,
+ message: { role: "assistant", content: collected.textContent },
+ finish_reason: timedOut ? "length" : collected.finishReason,
},
],
- ...(usage && { usage }),
+ ...(collected.usage && { usage: collected.usage }),
// Expose credit balance for upstream consumers (usage service, dashboard)
- ...(remainingCredits && { _remainingCredits: remainingCredits }),
+ ...(collected.remainingCredits && { _remainingCredits: collected.remainingCredits }),
};
const syntheticStatus = timedOut ? 504 : response.status;
diff --git a/open-sse/executors/base.ts b/open-sse/executors/base.ts
index 69e883e736..7c0b4e1087 100644
--- a/open-sse/executors/base.ts
+++ b/open-sse/executors/base.ts
@@ -474,7 +474,10 @@ export class BaseExecutor {
// cache_create (vs 96% cache_read with a stable prefix). Using a per-day
// hash keeps the billing header format while preserving cache affinity.
const dayStamp = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
- const fp = createHash("sha256").update(`${dayStamp}${ccVersion}`).digest("hex").slice(0, 3);
+ const fp = createHash("sha256")
+ .update(`${dayStamp}${ccVersion}`)
+ .digest("hex")
+ .slice(0, 3);
const billingLine = `x-anthropic-billing-header: cc_version=${ccVersion}.${fp}; cc_entrypoint=cli; cch=00000;`;
if (Array.isArray(tb.system)) {
diff --git a/open-sse/executors/codex.ts b/open-sse/executors/codex.ts
index 77074b0557..1eaebd3d68 100644
--- a/open-sse/executors/codex.ts
+++ b/open-sse/executors/codex.ts
@@ -895,7 +895,10 @@ export class CodexExecutor extends BaseExecutor {
* because all conversations share the same cache partition. (#1643)
* Ref: openai/codex core/src/client.rs line 853
*/
- private getPromptCacheSessionId(credentials, body: Record<string, unknown> | null): string | null {
+ private getPromptCacheSessionId(
+ credentials,
+ body: Record<string, unknown> | null
+ ): string | null {
// Prefer per-session identifiers from the client request body
const sessionId = body?.session_id ?? body?.conversation_id;
if (typeof sessionId === "string" && sessionId.length > 0) {
diff --git a/open-sse/executors/kiro.ts b/open-sse/executors/kiro.ts
index e9a75858c0..f4b7b2a1e2 100644
--- a/open-sse/executors/kiro.ts
+++ b/open-sse/executors/kiro.ts
@@ -15,11 +15,14 @@ type UsageSummary = {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
+ cache_read_input_tokens?: number;
+ cache_creation_input_tokens?: number;
};
type KiroStreamState = {
endDetected: boolean;
finishEmitted: boolean;
+ stopSeen: boolean;
hasToolCalls: boolean;
toolCallIndex: number;
seenToolIds: Map<string, number>;
@@ -35,6 +38,66 @@ type EventFrame = {
payload: JsonRecord | null;
};
+class ByteQueue {
+ private chunks: Uint8Array[] = [];
+ private headOffset = 0;
+ length = 0;
+
+ push(chunk: Uint8Array) {
+ if (!(chunk instanceof Uint8Array) || chunk.length === 0) return;
+ this.chunks.push(chunk);
+ this.length += chunk.length;
+ }
+
+ peekUint32BE(offset = 0): number | null {
+ if (this.length < offset + 4) return null;
+
+ let value = 0;
+ for (let i = 0; i < 4; i++) {
+ value = (value << 8) | this.byteAt(offset + i);
+ }
+ return value >>> 0;
+ }
+
+ read(length: number): Uint8Array | null {
+ if (length < 0 || this.length < length) return null;
+
+ const output = new Uint8Array(length);
+ let written = 0;
+
+ while (written < length) {
+ const head = this.chunks[0];
+ const available = head.length - this.headOffset;
+ const take = Math.min(available, length - written);
+ output.set(head.subarray(this.headOffset, this.headOffset + take), written);
+ written += take;
+ this.headOffset += take;
+ this.length -= take;
+
+ if (this.headOffset >= head.length) {
+ this.chunks.shift();
+ this.headOffset = 0;
+ }
+ }
+
+ return output;
+ }
+
+ private byteAt(offset: number): number {
+ let remaining = offset;
+ for (let i = 0; i < this.chunks.length; i++) {
+ const chunk = this.chunks[i];
+ const start = i === 0 ? this.headOffset : 0;
+ const available = chunk.length - start;
+ if (remaining < available) {
+ return chunk[start + remaining];
+ }
+ remaining -= available;
+ }
+ return 0;
+ }
+}
+
// ── CRC32 lookup table (IEEE polynomial, no dependency) ──
const CRC32_TABLE = new Uint32Array(256);
const TEXT_ENCODER = new TextEncoder();
@@ -55,6 +118,56 @@ function crc32(buf: Uint8Array) {
return (crc ^ 0xffffffff) >>> 0;
}
+function buildKiroFinishChunk(
+ state: KiroStreamState,
+ responseId: string,
+ created: number,
+ model: string,
+ includeUsage: boolean
+): JsonRecord {
+ const finishChunk: JsonRecord = {
+ id: responseId,
+ object: "chat.completion.chunk",
+ created,
+ model,
+ choices: [
+ {
+ index: 0,
+ delta: {},
+ finish_reason: state.hasToolCalls ? "tool_calls" : "stop",
+ },
+ ],
+ };
+
+ if (includeUsage && state.usage) {
+ finishChunk.usage = state.usage;
+ }
+
+ return finishChunk;
+}
+
+function ensureKiroUsage(state: KiroStreamState) {
+ if (state.usage) return;
+
+ const estimatedOutputTokens =
+ state.totalContentLength && state.totalContentLength > 0
+ ? Math.max(1, Math.floor(state.totalContentLength / 4))
+ : 0;
+
+ const estimatedInputTokens =
+ state.contextUsagePercentage && state.contextUsagePercentage > 0
+ ? Math.floor((state.contextUsagePercentage * 200000) / 100)
+ : 0;
+
+ if (estimatedInputTokens <= 0 && estimatedOutputTokens <= 0) return;
+
+ state.usage = {
+ prompt_tokens: estimatedInputTokens,
+ completion_tokens: estimatedOutputTokens,
+ total_tokens: estimatedInputTokens + estimatedOutputTokens,
+ };
+}
+
/**
* KiroExecutor - Executor for Kiro AI (AWS CodeWhisperer)
* Uses AWS CodeWhisperer streaming API with AWS EventStream binary format
@@ -131,13 +244,14 @@ export class KiroExecutor extends BaseExecutor {
* Using TransformStream instead of ReadableStream.pull() to avoid Workers timeout
*/
transformEventStreamToSSE(response: Response, model: string) {
- let buffer = new Uint8Array(0);
+ const buffer = new ByteQueue();
let chunkIndex = 0;
const responseId = `chatcmpl-${Date.now()}`;
const created = Math.floor(Date.now() / 1000);
const state: KiroStreamState = {
endDetected: false,
finishEmitted: false,
+ stopSeen: false,
hasToolCalls: false,
toolCallIndex: 0,
seenToolIds: new Map(),
@@ -145,24 +259,19 @@ export class KiroExecutor extends BaseExecutor {
const transformStream = new TransformStream({
async transform(chunk, controller) {
- // Append to buffer
- const newBuffer = new Uint8Array(buffer.length + chunk.length);
- newBuffer.set(buffer);
- newBuffer.set(chunk, buffer.length);
- buffer = newBuffer;
+ buffer.push(chunk);
// Parse events from buffer
let iterations = 0;
const maxIterations = 1000;
while (buffer.length >= 16 && iterations < maxIterations) {
iterations++;
- const view = new DataView(buffer.buffer, buffer.byteOffset);
- const totalLength = view.getUint32(0, false);
+ const totalLength = buffer.peekUint32BE(0);
- if (totalLength < 16 || totalLength > buffer.length || buffer.length < totalLength) break;
+ if (!totalLength || totalLength < 16 || totalLength > buffer.length) break;
- const eventData = buffer.slice(0, totalLength);
- buffer = buffer.slice(totalLength);
+ const eventData = buffer.read(totalLength);
+ if (!eventData) break;
const event = parseEventFrame(eventData);
if (!event) continue;
@@ -308,21 +417,7 @@ export class KiroExecutor extends BaseExecutor {
// Handle messageStopEvent
if (eventType === "messageStopEvent") {
- const chunk: JsonRecord = {
- id: responseId,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [
- {
- index: 0,
- delta: {},
- finish_reason: state.hasToolCalls ? "tool_calls" : "stop",
- },
- ],
- };
- state.finishEmitted = true;
- controller.enqueue(TEXT_ENCODER.encode(`data: ${JSON.stringify(chunk)}\n\n`));
+ state.stopSeen = true;
}
// Handle contextUsageEvent to extract contextUsagePercentage
@@ -381,54 +476,6 @@ export class KiroExecutor extends BaseExecutor {
}
}
}
-
- // Emit final chunk only after receiving BOTH meteringEvent AND contextUsageEvent
- if (state.hasMeteringEvent && state.hasContextUsage && !state.finishEmitted) {
- state.finishEmitted = true;
-
- // Estimate tokens if not available from events
- if (!state.usage) {
- // Estimate output tokens from content length
- const estimatedOutputTokens =
- state.totalContentLength > 0
- ? Math.max(1, Math.floor(state.totalContentLength / 4))
- : 0;
-
- // Estimate input tokens from contextUsagePercentage
- // Kiro models typically have 200k context window
- const estimatedInputTokens =
- state.contextUsagePercentage > 0
- ? Math.floor((state.contextUsagePercentage * 200000) / 100)
- : 0;
-
- state.usage = {
- prompt_tokens: estimatedInputTokens,
- completion_tokens: estimatedOutputTokens,
- total_tokens: estimatedInputTokens + estimatedOutputTokens,
- };
- }
-
- const finishChunk: JsonRecord = {
- id: responseId,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [
- {
- index: 0,
- delta: {},
- finish_reason: state.hasToolCalls ? "tool_calls" : "stop",
- },
- ],
- };
-
- // Include usage in final chunk if available
- if (state.usage) {
- finishChunk.usage = state.usage;
- }
-
- controller.enqueue(TEXT_ENCODER.encode(`data: ${JSON.stringify(finishChunk)}\n\n`));
- }
}
if (iterations >= maxIterations) {
@@ -440,19 +487,8 @@ export class KiroExecutor extends BaseExecutor {
// Emit finish chunk if not already sent
if (!state.finishEmitted) {
state.finishEmitted = true;
- const finishChunk = {
- id: responseId,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [
- {
- index: 0,
- delta: {},
- finish_reason: state.hasToolCalls ? "tool_calls" : "stop",
- },
- ],
- };
+ ensureKiroUsage(state);
+ const finishChunk = buildKiroFinishChunk(state, responseId, created, model, true);
controller.enqueue(TEXT_ENCODER.encode(`data: ${JSON.stringify(finishChunk)}\n\n`));
}
diff --git a/open-sse/utils/requestLogger.ts b/open-sse/utils/requestLogger.ts
index f1b8460e55..f18d765f2d 100644
--- a/open-sse/utils/requestLogger.ts
+++ b/open-sse/utils/requestLogger.ts
@@ -44,9 +44,11 @@ type RequestLoggerOptions = {
enabled?: boolean;
captureStreamChunks?: boolean;
maxStreamChunkBytes?: number;
+ maxStreamChunkItems?: number;
};
const DEFAULT_MAX_STREAM_CHUNK_BYTES = 128 * 1024;
+const DEFAULT_MAX_STREAM_CHUNK_ITEMS = 512;
const MAX_LOG_STRING_LENGTH = 64 * 1024;
const MAX_LOG_ARRAY_ITEMS = 24;
const MAX_LOG_OBJECT_KEYS = 80;
@@ -129,11 +131,17 @@ function appendBoundedChunk(
chunks: string[],
bytes: { value: number; truncated: boolean },
chunk: string,
- maxBytes: number
+ 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;
@@ -147,7 +155,9 @@ function appendBoundedChunk(
}
chunks.push(chunk.slice(0, remaining));
- chunks.push(`[stream chunk log truncated after ${maxBytes} bytes]`);
+ if (chunks.length < maxItems) {
+ chunks.push(`[stream chunk log truncated after ${maxBytes} bytes]`);
+ }
bytes.value = maxBytes;
bytes.truncated = true;
}
@@ -218,6 +228,10 @@ export async function createRequestLogger(
Number.isInteger(options.maxStreamChunkBytes) && Number(options.maxStreamChunkBytes) > 0
? Number(options.maxStreamChunkBytes)
: DEFAULT_MAX_STREAM_CHUNK_BYTES;
+ const maxStreamChunkItems =
+ Number.isInteger(options.maxStreamChunkItems) && Number(options.maxStreamChunkItems) > 0
+ ? Number(options.maxStreamChunkItems)
+ : DEFAULT_MAX_STREAM_CHUNK_ITEMS;
const streamChunks = createEmptyStreamChunks();
const streamChunkBytes = {
provider: { value: 0, truncated: false },
@@ -272,13 +286,20 @@ export async function createRequestLogger(
streamChunks.provider,
streamChunkBytes.provider,
chunk,
- maxStreamChunkBytes
+ maxStreamChunkBytes,
+ maxStreamChunkItems
);
},
appendOpenAIChunk(chunk) {
if (!captureStreamChunks) return;
- appendBoundedChunk(streamChunks.openai, streamChunkBytes.openai, chunk, maxStreamChunkBytes);
+ appendBoundedChunk(
+ streamChunks.openai,
+ streamChunkBytes.openai,
+ chunk,
+ maxStreamChunkBytes,
+ maxStreamChunkItems
+ );
},
logConvertedResponse(body) {
@@ -290,7 +311,13 @@ export async function createRequestLogger(
appendConvertedChunk(chunk) {
if (!captureStreamChunks) return;
- appendBoundedChunk(streamChunks.client, streamChunkBytes.client, chunk, maxStreamChunkBytes);
+ appendBoundedChunk(
+ streamChunks.client,
+ streamChunkBytes.client,
+ chunk,
+ maxStreamChunkBytes,
+ maxStreamChunkItems
+ );
},
logError(error, requestBody = null) {
diff --git a/src/lib/usage/callLogArtifacts.ts b/src/lib/usage/callLogArtifacts.ts
index 6d8e1b94a5..b48df4a20a 100644
--- a/src/lib/usage/callLogArtifacts.ts
+++ b/src/lib/usage/callLogArtifacts.ts
@@ -8,6 +8,7 @@ const isBuildPhase = process.env.NEXT_PHASE === "phase-production-build";
const DATA_DIR = resolveDataDir({ isCloud });
export const CALL_LOGS_DIR = isCloud ? null : path.join(DATA_DIR, "call_logs");
+export const MAX_CALL_LOG_ARTIFACT_BYTES = 512 * 1024;
export type CallLogDetailState = "none" | "ready" | "missing" | "corrupt" | "legacy-inline";
@@ -72,6 +73,92 @@ function computeArtifactChecksum(serialized: string): string {
return hash.toString(16).padStart(8, "0");
}
+function truncateArtifactForStorage(artifact: CallLogArtifact): CallLogArtifact {
+ const pipeline = artifact.pipeline;
+ if (!pipeline?.streamChunks) return artifact;
+
+ return {
+ ...artifact,
+ pipeline: {
+ ...pipeline,
+ streamChunks: {
+ provider: pipeline.streamChunks.provider?.length
+ ? ["[stream chunks omitted: call log artifact size limit exceeded]"]
+ : undefined,
+ openai: pipeline.streamChunks.openai?.length
+ ? ["[stream chunks omitted: call log artifact size limit exceeded]"]
+ : undefined,
+ client: pipeline.streamChunks.client?.length
+ ? ["[stream chunks omitted: call log artifact size limit exceeded]"]
+ : undefined,
+ },
+ },
+ };
+}
+
+function omitOversizedPipeline(artifact: CallLogArtifact): CallLogArtifact {
+ if (!artifact.pipeline) return artifact;
+
+ return {
+ ...artifact,
+ pipeline: {
+ error: {
+ _omniroute_truncated: true,
+ reason: "call_log_artifact_size_limit_exceeded",
+ },
+ },
+ };
+}
+
+function serializeArtifactForStorage(artifact: CallLogArtifact): string {
+ const serialized = JSON.stringify(artifact, null, 2);
+ if (Buffer.byteLength(serialized) <= MAX_CALL_LOG_ARTIFACT_BYTES) {
+ return serialized;
+ }
+
+ const truncated = JSON.stringify(truncateArtifactForStorage(artifact), null, 2);
+ if (Buffer.byteLength(truncated) <= MAX_CALL_LOG_ARTIFACT_BYTES) {
+ return truncated;
+ }
+
+ const withoutPipeline = JSON.stringify(omitOversizedPipeline(artifact), null, 2);
+ if (Buffer.byteLength(withoutPipeline) <= MAX_CALL_LOG_ARTIFACT_BYTES) {
+ return withoutPipeline;
+ }
+
+ const minimal = JSON.stringify(
+ {
+ ...omitOversizedPipeline(artifact),
+ requestBody: "[omitted: call log artifact size limit exceeded]",
+ responseBody: "[omitted: call log artifact size limit exceeded]",
+ error: artifact.error ? "[omitted: call log artifact size limit exceeded]" : null,
+ },
+ null,
+ 2
+ );
+ if (Buffer.byteLength(minimal) <= MAX_CALL_LOG_ARTIFACT_BYTES) {
+ return minimal;
+ }
+
+ return JSON.stringify(
+ {
+ schemaVersion: artifact.schemaVersion,
+ summary: artifact.summary,
+ requestBody: "[omitted: call log artifact size limit exceeded]",
+ responseBody: "[omitted: call log artifact size limit exceeded]",
+ error: artifact.error ? "[omitted: call log artifact size limit exceeded]" : null,
+ pipeline: {
+ error: {
+ _omniroute_truncated: true,
+ reason: "call_log_artifact_size_limit_exceeded",
+ },
+ },
+ },
+ null,
+ 2
+ );
+}
+
export function writeCallArtifact(
artifact: CallLogArtifact,
relativePath = buildArtifactRelativePath(artifact.summary.timestamp, artifact.summary.id)
@@ -82,7 +169,7 @@ export function writeCallArtifact(
const tmpPath = `${absPath}.${process.pid}.${Date.now()}.tmp`;
try {
- const serialized = JSON.stringify(artifact, null, 2);
+ const serialized = serializeArtifactForStorage(artifact);
const sizeBytes = Buffer.byteLength(serialized);
// Keep the legacy field name for storage compatibility, but use a non-cryptographic checksum
// so artifact bookkeeping is not treated as password hashing by static analysis.
diff --git a/tests/unit/call-log-cap.test.ts b/tests/unit/call-log-cap.test.ts
index 7c093a2a56..7b3ac1fb0c 100644
--- a/tests/unit/call-log-cap.test.ts
+++ b/tests/unit/call-log-cap.test.ts
@@ -452,6 +452,95 @@ test("saveCallLog keeps large payloads out of SQLite while preserving explicit d
assert.equal((exported[0] as any).requestBody.payload.length, requestBody.payload.length);
});
+test("saveCallLog truncates oversized call log artifacts for storage", async () => {
+ const hugeChunk = "x".repeat(600 * 1024);
+
+ await callLogs.saveCallLog({
+ id: "truncated-artifact",
+ timestamp: "2026-03-31T10:05:00.000Z",
+ method: "POST",
+ path: "/v1/chat/completions",
+ status: 200,
+ model: "openai/gpt-4.1",
+ provider: "openai",
+ requestBody: { payload: "request" },
+ responseBody: { output: "response" },
+ pipelinePayloads: {
+ streamChunks: {
+ provider: [hugeChunk],
+ openai: [hugeChunk],
+ client: [hugeChunk],
+ },
+ },
+ });
+
+ const db = core.getDbInstance();
+ const row = db
+ .prepare(
+ `
+ SELECT artifact_relpath, artifact_size_bytes, detail_state
+ FROM call_logs WHERE id = ?
+ `
+ )
+ .get("truncated-artifact");
+ assert.equal((row as any).detail_state, "ready");
+ assert.ok((row as any).artifact_size_bytes <= 512 * 1024);
+
+ const artifactPath = path.join(TEST_DATA_DIR, "call_logs", (row as any).artifact_relpath);
+ const artifact = JSON.parse(fs.readFileSync(artifactPath, "utf8"));
+ assert.deepEqual(artifact.requestBody, { payload: "request" });
+ assert.deepEqual(artifact.responseBody, { output: "response" });
+ assert.equal(artifact.error, null);
+ assert.deepEqual(artifact.pipeline.streamChunks, {
+ provider: ["[stream chunks omitted: call log artifact size limit exceeded]"],
+ openai: ["[stream chunks omitted: call log artifact size limit exceeded]"],
+ client: ["[stream chunks omitted: call log artifact size limit exceeded]"],
+ });
+});
+
+test("saveCallLog omits oversized non-stream pipeline payloads to enforce artifact cap", async () => {
+ const hugePayload = "x".repeat(600 * 1024);
+
+ await callLogs.saveCallLog({
+ id: "truncated-pipeline-artifact",
+ timestamp: "2026-03-31T10:06:00.000Z",
+ method: "POST",
+ path: "/v1/chat/completions",
+ status: 200,
+ model: "openai/gpt-4.1",
+ provider: "openai",
+ requestBody: { payload: "request" },
+ responseBody: { output: "response" },
+ pipelinePayloads: {
+ providerRequest: { body: hugePayload },
+ providerResponse: { body: hugePayload },
+ },
+ });
+
+ const db = core.getDbInstance();
+ const row = db
+ .prepare(
+ `
+ SELECT artifact_relpath, artifact_size_bytes, detail_state
+ FROM call_logs WHERE id = ?
+ `
+ )
+ .get("truncated-pipeline-artifact");
+ assert.equal((row as any).detail_state, "ready");
+ assert.ok((row as any).artifact_size_bytes <= 512 * 1024);
+
+ const artifactPath = path.join(TEST_DATA_DIR, "call_logs", (row as any).artifact_relpath);
+ const artifact = JSON.parse(fs.readFileSync(artifactPath, "utf8"));
+ assert.deepEqual(artifact.requestBody, { payload: "request" });
+ assert.deepEqual(artifact.responseBody, { output: "response" });
+ assert.deepEqual(artifact.pipeline, {
+ error: {
+ _omniroute_truncated: true,
+ reason: "call_log_artifact_size_limit_exceeded",
+ },
+ });
+});
+
test("saveCallLog logs and returns when sqlite persistence throws unexpectedly", async () => {
const db = core.getDbInstance();
const originalPrepare = db.prepare;
diff --git a/tests/unit/executor-antigravity.test.ts b/tests/unit/executor-antigravity.test.ts
index 0e9eed230b..ef00b53c34 100644
--- a/tests/unit/executor-antigravity.test.ts
+++ b/tests/unit/executor-antigravity.test.ts
@@ -244,6 +244,70 @@ test("AntigravityExecutor.collectStreamToResponse turns SSE Gemini chunks into a
});
});
+test("AntigravityExecutor.collectStreamToResponse parses fragmented SSE lines incrementally", async () => {
+ const executor = new AntigravityExecutor();
+ const encoder = new TextEncoder();
+ const streamText = [
+ `data: ${JSON.stringify({
+ response: {
+ candidates: [{ content: { parts: [{ text: "Frag" }] } }],
+ },
+ })}\n\n`,
+ `data: ${JSON.stringify({
+ response: {
+ candidates: [
+ {
+ content: { parts: [{ text: "mented" }] },
+ finishReason: "STOP",
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 9,
+ candidatesTokenCount: 4,
+ totalTokenCount: 13,
+ },
+ },
+ })}\n\n`,
+ ].join("");
+ const response = new Response(
+ new ReadableStream({
+ start(controller) {
+ for (const chunk of [
+ streamText.slice(0, 6),
+ streamText.slice(6, 31),
+ streamText.slice(31, 79),
+ streamText.slice(79, 143),
+ streamText.slice(143),
+ ]) {
+ controller.enqueue(encoder.encode(chunk));
+ }
+ controller.close();
+ },
+ }),
+ {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ }
+ );
+
+ const result = await executor.collectStreamToResponse(
+ response,
+ "gemini-2.5-flash",
+ "https://example.com",
+ { Authorization: "Bearer ag-token" },
+ { request: {} }
+ );
+ const payload = (await result.response.json()) as any;
+
+ assert.equal(payload.choices[0].message.content, "Fragmented");
+ assert.equal(payload.choices[0].finish_reason, "stop");
+ assert.deepEqual(payload.usage, {
+ prompt_tokens: 9,
+ completion_tokens: 4,
+ total_tokens: 13,
+ });
+});
+
test("AntigravityExecutor.refreshCredentials refreshes Google OAuth tokens", async () => {
const executor = new AntigravityExecutor();
const originalFetch = globalThis.fetch;
diff --git a/tests/unit/executor-kiro.test.ts b/tests/unit/executor-kiro.test.ts
index 1a6bc1c2ee..06e7234f20 100644
--- a/tests/unit/executor-kiro.test.ts
+++ b/tests/unit/executor-kiro.test.ts
@@ -69,11 +69,15 @@ function buildEventFrame(eventType, payload) {
}
function buildEventStreamResponse(frames) {
+ return buildEventStreamResponseFromChunks(frames);
+}
+
+function buildEventStreamResponseFromChunks(chunks) {
return new Response(
new ReadableStream({
start(controller) {
- for (const frame of frames) {
- controller.enqueue(frame);
+ for (const chunk of chunks) {
+ controller.enqueue(chunk);
}
controller.close();
},
@@ -85,6 +89,15 @@ function buildEventStreamResponse(frames) {
);
}
+function parseSSEJsonChunks(text) {
+ return text
+ .split("\n")
+ .filter((line) => line.startsWith("data: "))
+ .map((line) => line.slice(6).trim())
+ .filter((payload) => payload && payload !== "[DONE]")
+ .map((payload) => JSON.parse(payload));
+}
+
test("KiroExecutor.buildHeaders includes Kiro-specific auth and metadata", () => {
const executor = new KiroExecutor();
const headers = executor.buildHeaders({ accessToken: "kiro-token" }, true);
@@ -150,6 +163,39 @@ test("KiroExecutor.transformEventStreamToSSE converts text, tool calls, usage an
assert.match(text, /\[DONE\]/);
});
+test("KiroExecutor.transformEventStreamToSSE parses fragmented frames and waits for post-stop usage", async () => {
+ const executor = new KiroExecutor();
+ const bytes = concatArrays(
+ buildEventFrame("assistantResponseEvent", { content: "Hello fragmented" }),
+ buildEventFrame("messageStopEvent", {}),
+ buildEventFrame("metricsEvent", { inputTokens: 11, outputTokens: 13 }),
+ buildEventFrame("contextUsageEvent", { contextUsagePercentage: 17 }),
+ buildEventFrame("meteringEvent", {})
+ );
+ const response = buildEventStreamResponseFromChunks([
+ bytes.subarray(0, 2),
+ bytes.subarray(2, 9),
+ bytes.subarray(9, 37),
+ bytes.subarray(37, 91),
+ bytes.subarray(91),
+ ]);
+
+ const transformed = executor.transformEventStreamToSSE(response, "kiro-model");
+ const text = await transformed.text();
+ const chunks = parseSSEJsonChunks(text);
+ const finishChunks = chunks.filter((chunk) => chunk.choices?.[0]?.finish_reason);
+
+ assert.match(text, /"content":"Hello fragmented"/);
+ assert.equal(finishChunks.length, 1);
+ assert.equal(finishChunks[0].choices[0].finish_reason, "stop");
+ assert.deepEqual(finishChunks[0].usage, {
+ prompt_tokens: 11,
+ completion_tokens: 13,
+ total_tokens: 24,
+ });
+ assert.match(text, /\[DONE\]/);
+});
+
test("KiroExecutor.transformEventStreamToSSE deduplicates tool starts and handles malformed payload JSON", async () => {
const executor = new KiroExecutor();
const response = buildEventStreamResponse([
diff --git a/tests/unit/stream-utils.test.ts b/tests/unit/stream-utils.test.ts
index 594327ff87..e48bb1d79c 100644
--- a/tests/unit/stream-utils.test.ts
+++ b/tests/unit/stream-utils.test.ts
@@ -953,3 +953,22 @@ test("createRequestLogger skips disabled logs and caps retained stream chunk byt
"[stream chunk log truncated after 5 bytes]",
]);
});
+
+test("createRequestLogger caps retained stream chunk item count", async () => {
+ const logger = await createRequestLogger("openai", "openai", "gpt-test", {
+ enabled: true,
+ captureStreamChunks: true,
+ maxStreamChunkBytes: 1024,
+ maxStreamChunkItems: 2,
+ });
+
+ logger.appendProviderChunk("one");
+ logger.appendProviderChunk("two");
+ logger.appendProviderChunk("three");
+
+ const payloads = logger.getPipelinePayloads();
+ assert.deepEqual(payloads.streamChunks.provider, [
+ "one",
+ "[stream chunk log truncated after 2 chunks]",
+ ]);
+});