const require_helpers = require('./helpers.cjs');
const require_router = require('./router.cjs');
const require_sse_writer = require('./sse-writer.cjs');
const require_interruption = require('./interruption.cjs');
const require_chaos = require('./chaos.cjs');
const require_recorder = require('./recorder.cjs');

//#region src/gemini.ts
function geminiToCompletionRequest(req, model, stream) {
	const messages = [];
	if (req.systemInstruction) {
		const text = req.systemInstruction.parts.filter((p) => p.text !== void 0).map((p) => p.text).join("");
		if (text) messages.push({
			role: "system",
			content: text
		});
	}
	if (req.contents) {
		let callCounter = 0;
		for (const content of req.contents) {
			const role = content.role ?? "user";
			if (role === "user") {
				const funcResponses = content.parts.filter((p) => p.functionResponse);
				const textParts = content.parts.filter((p) => p.text !== void 0 && !p.thought);
				if (funcResponses.length > 0) {
					const lastAssistant = [...messages].reverse().find((m) => m.role === "assistant" && m.tool_calls);
					const matchedToolCallIds = /* @__PURE__ */ new Set();
					for (const part of funcResponses) {
						const matchingCall = lastAssistant?.tool_calls?.find((tc) => tc.function.name === part.functionResponse.name && !matchedToolCallIds.has(tc.id));
						if (matchingCall) matchedToolCallIds.add(matchingCall.id);
						const toolCallId = matchingCall?.id ?? `call_gemini_${part.functionResponse.name}_${callCounter++}`;
						messages.push({
							role: "tool",
							content: typeof part.functionResponse.response === "string" ? part.functionResponse.response : JSON.stringify(part.functionResponse.response),
							tool_call_id: toolCallId
						});
					}
					if (textParts.length > 0) messages.push({
						role: "user",
						content: textParts.map((p) => p.text).join("")
					});
				} else {
					const text = textParts.map((p) => p.text).join("");
					messages.push({
						role: "user",
						content: text
					});
				}
			} else if (role === "model") {
				const funcCalls = content.parts.filter((p) => p.functionCall);
				const textParts = content.parts.filter((p) => p.text !== void 0 && !p.thought);
				if (funcCalls.length > 0) {
					const text = textParts.map((p) => p.text).join("");
					messages.push({
						role: "assistant",
						content: text || null,
						tool_calls: funcCalls.map((fc, i) => ({
							id: fc.functionCall.id ?? `call_gemini_${fc.functionCall.name}_${i}`,
							type: "function",
							function: {
								name: fc.functionCall.name,
								arguments: JSON.stringify(fc.functionCall.args ?? {})
							}
						}))
					});
				} else {
					const text = textParts.map((p) => p.text).join("");
					messages.push({
						role: "assistant",
						content: text
					});
				}
			}
		}
	}
	let tools;
	if (req.tools && req.tools.length > 0) {
		const decls = req.tools.flatMap((t) => t.functionDeclarations ?? []);
		if (decls.length > 0) tools = decls.map((d) => ({
			type: "function",
			function: {
				name: d.name,
				description: d.description,
				parameters: d.parameters
			}
		}));
	}
	return {
		model,
		messages,
		stream,
		temperature: req.generationConfig?.temperature,
		max_tokens: req.generationConfig?.maxOutputTokens,
		top_p: req.generationConfig?.topP,
		top_k: req.generationConfig?.topK,
		tools
	};
}
function geminiFinishReason(finishReason, defaultReason) {
	if (!finishReason) return defaultReason;
	if (finishReason === "stop") return "STOP";
	if (finishReason === "tool_calls") return "FUNCTION_CALL";
	if (finishReason === "length") return "MAX_TOKENS";
	if (finishReason === "content_filter") return "SAFETY";
	return finishReason;
}
function geminiUsageMetadata(overrides) {
	if (!overrides?.usage) return {
		promptTokenCount: 0,
		candidatesTokenCount: 0,
		totalTokenCount: 0
	};
	const prompt = overrides.usage.promptTokenCount ?? overrides.usage.prompt_tokens ?? overrides.usage.input_tokens ?? 0;
	const candidates = overrides.usage.candidatesTokenCount ?? overrides.usage.completion_tokens ?? overrides.usage.output_tokens ?? 0;
	return {
		promptTokenCount: prompt,
		candidatesTokenCount: candidates,
		totalTokenCount: overrides.usage.totalTokenCount ?? prompt + candidates
	};
}
function buildGeminiTextStreamChunks(content, chunkSize, reasoning, overrides) {
	const chunks = [];
	const effectiveFinish = geminiFinishReason(overrides?.finishReason, "STOP");
	const usage = geminiUsageMetadata(overrides);
	if (reasoning) for (let i = 0; i < reasoning.length; i += chunkSize) {
		const slice = reasoning.slice(i, i + chunkSize);
		chunks.push({ candidates: [{
			content: {
				role: "model",
				parts: [{
					text: slice,
					thought: true
				}]
			},
			index: 0
		}] });
	}
	for (let i = 0; i < content.length; i += chunkSize) {
		const slice = content.slice(i, i + chunkSize);
		const isLast = i + chunkSize >= content.length;
		const chunk = {
			candidates: [{
				content: {
					role: "model",
					parts: [{ text: slice }]
				},
				index: 0,
				...isLast ? { finishReason: effectiveFinish } : {}
			}],
			...isLast ? { usageMetadata: usage } : {}
		};
		chunks.push(chunk);
	}
	if (content.length === 0) chunks.push({
		candidates: [{
			content: {
				role: "model",
				parts: [{ text: "" }]
			},
			finishReason: effectiveFinish,
			index: 0
		}],
		usageMetadata: usage
	});
	return chunks;
}
function parseToolCallPart(tc, logger) {
	let argsObj;
	try {
		argsObj = JSON.parse(tc.arguments || "{}");
	} catch {
		logger.warn(`Malformed JSON in fixture tool call arguments for "${tc.name}": ${tc.arguments}`);
		argsObj = {};
	}
	const functionCall = {
		name: tc.name,
		args: argsObj
	};
	if (tc.id) functionCall.id = tc.id;
	return { functionCall };
}
function buildGeminiToolCallStreamChunks(toolCalls, chunkSize, logger, reasoning, overrides) {
	const chunks = [];
	if (reasoning) for (let i = 0; i < reasoning.length; i += chunkSize) {
		const slice = reasoning.slice(i, i + chunkSize);
		chunks.push({ candidates: [{
			content: {
				role: "model",
				parts: [{
					text: slice,
					thought: true
				}]
			},
			index: 0
		}] });
	}
	const parts = toolCalls.map((tc) => parseToolCallPart(tc, logger));
	chunks.push({
		candidates: [{
			content: {
				role: "model",
				parts
			},
			finishReason: geminiFinishReason(overrides?.finishReason, "FUNCTION_CALL"),
			index: 0
		}],
		usageMetadata: geminiUsageMetadata(overrides)
	});
	return chunks;
}
function buildGeminiTextResponse(content, reasoning, overrides) {
	const parts = [];
	if (reasoning) parts.push({
		text: reasoning,
		thought: true
	});
	parts.push({ text: content });
	return {
		candidates: [{
			content: {
				role: "model",
				parts
			},
			finishReason: geminiFinishReason(overrides?.finishReason, "STOP"),
			index: 0
		}],
		usageMetadata: geminiUsageMetadata(overrides)
	};
}
function buildGeminiToolCallResponse(toolCalls, logger, reasoning, overrides) {
	const parts = [];
	if (reasoning) parts.push({
		text: reasoning,
		thought: true
	});
	parts.push(...toolCalls.map((tc) => parseToolCallPart(tc, logger)));
	return {
		candidates: [{
			content: {
				role: "model",
				parts
			},
			finishReason: geminiFinishReason(overrides?.finishReason, "FUNCTION_CALL"),
			index: 0
		}],
		usageMetadata: geminiUsageMetadata(overrides)
	};
}
function buildGeminiContentWithToolCallsStreamChunks(content, toolCalls, chunkSize, logger, reasoning, overrides, blocks) {
	const chunks = [];
	if (reasoning) for (let i = 0; i < reasoning.length; i += chunkSize) {
		const slice = reasoning.slice(i, i + chunkSize);
		chunks.push({ candidates: [{
			content: {
				role: "model",
				parts: [{
					text: slice,
					thought: true
				}]
			},
			index: 0
		}] });
	}
	if (blocks && blocks.length > 0) {
		const resolved = require_helpers.resolveFixtureBlocks(blocks);
		resolved.forEach((block, i) => {
			const isLast = i === resolved.length - 1;
			const finishReason = isLast ? geminiFinishReason(overrides?.finishReason, "FUNCTION_CALL") : void 0;
			if (block.type === "toolCall") {
				const part = parseToolCallPart({
					name: block.name,
					arguments: block.arguments,
					id: block.id
				}, logger);
				chunks.push({
					candidates: [{
						content: {
							role: "model",
							parts: [part]
						},
						...finishReason ? { finishReason } : {},
						index: 0
					}],
					...isLast ? { usageMetadata: geminiUsageMetadata(overrides) } : {}
				});
			} else {
				const text = block.text;
				if (text.length === 0) chunks.push({
					candidates: [{
						content: {
							role: "model",
							parts: [{ text: "" }]
						},
						...finishReason ? { finishReason } : {},
						index: 0
					}],
					...isLast ? { usageMetadata: geminiUsageMetadata(overrides) } : {}
				});
				else for (let j = 0; j < text.length; j += chunkSize) {
					const slice = text.slice(j, j + chunkSize);
					const lastSlice = j + chunkSize >= text.length;
					const sliceFinish = isLast && lastSlice ? finishReason : void 0;
					chunks.push({
						candidates: [{
							content: {
								role: "model",
								parts: [{ text: slice }]
							},
							...sliceFinish ? { finishReason: sliceFinish } : {},
							index: 0
						}],
						...isLast && lastSlice ? { usageMetadata: geminiUsageMetadata(overrides) } : {}
					});
				}
			}
		});
		return chunks;
	}
	if (content.length === 0) chunks.push({ candidates: [{
		content: {
			role: "model",
			parts: [{ text: "" }]
		},
		index: 0
	}] });
	else for (let i = 0; i < content.length; i += chunkSize) {
		const slice = content.slice(i, i + chunkSize);
		chunks.push({ candidates: [{
			content: {
				role: "model",
				parts: [{ text: slice }]
			},
			index: 0
		}] });
	}
	const parts = toolCalls.map((tc) => parseToolCallPart(tc, logger));
	chunks.push({
		candidates: [{
			content: {
				role: "model",
				parts
			},
			finishReason: geminiFinishReason(overrides?.finishReason, "FUNCTION_CALL"),
			index: 0
		}],
		usageMetadata: geminiUsageMetadata(overrides)
	});
	return chunks;
}
function buildGeminiContentWithToolCallsResponse(content, toolCalls, logger, reasoning, overrides, blocks) {
	const parts = [];
	if (reasoning) parts.push({
		text: reasoning,
		thought: true
	});
	if (blocks && blocks.length > 0) {
		const resolved = require_helpers.resolveFixtureBlocks(blocks);
		for (const block of resolved) if (block.type === "toolCall") parts.push(parseToolCallPart({
			name: block.name,
			arguments: block.arguments,
			id: block.id
		}, logger));
		else parts.push({ text: block.text });
	} else {
		parts.push({ text: content });
		parts.push(...toolCalls.map((tc) => parseToolCallPart(tc, logger)));
	}
	return {
		candidates: [{
			content: {
				role: "model",
				parts
			},
			finishReason: geminiFinishReason(overrides?.finishReason, "FUNCTION_CALL"),
			index: 0
		}],
		usageMetadata: geminiUsageMetadata(overrides)
	};
}
function resolveAudioInlineData(audio) {
	if (typeof audio.audio === "string") return {
		mimeType: require_helpers.formatToMime(audio.format ?? "mp3"),
		data: audio.audio
	};
	return {
		mimeType: audio.audio.contentType ?? "audio/mpeg",
		data: audio.audio.b64Json
	};
}
function buildGeminiAudioParts(audio, logger, effReasoning) {
	const parts = [{ inlineData: resolveAudioInlineData(audio) }];
	if (effReasoning) parts.push({
		text: effReasoning,
		thought: true
	});
	if (audio.content) parts.push({ text: audio.content });
	if (audio.toolCalls?.length) parts.push(...audio.toolCalls.map((tc) => parseToolCallPart(tc, logger)));
	return parts;
}
function buildGeminiAudioResponse(audio, logger, effReasoning) {
	return {
		candidates: [{
			content: {
				role: "model",
				parts: buildGeminiAudioParts(audio, logger, effReasoning)
			},
			finishReason: audio.toolCalls?.length ? "FUNCTION_CALL" : "STOP",
			index: 0
		}],
		usageMetadata: {
			promptTokenCount: 0,
			candidatesTokenCount: 0,
			totalTokenCount: 0
		}
	};
}
function buildGeminiAudioStreamChunks(audio, logger, effReasoning) {
	return [{
		candidates: [{
			content: {
				role: "model",
				parts: buildGeminiAudioParts(audio, logger, effReasoning)
			},
			finishReason: audio.toolCalls?.length ? "FUNCTION_CALL" : "STOP",
			index: 0
		}],
		usageMetadata: {
			promptTokenCount: 0,
			candidatesTokenCount: 0,
			totalTokenCount: 0
		}
	}];
}
async function writeGeminiSSEStream(res, chunks, optionsOrLatency) {
	const opts = typeof optionsOrLatency === "number" ? { latency: optionsOrLatency } : optionsOrLatency ?? {};
	const latency = opts.latency ?? 0;
	const profile = opts.streamingProfile;
	const { recordedTimings, replaySpeed } = opts;
	const signal = opts.signal;
	const onChunkSent = opts.onChunkSent;
	if (res.writableEnded) return true;
	res.setHeader("Content-Type", "text/event-stream");
	res.setHeader("Cache-Control", "no-cache");
	res.setHeader("Connection", "keep-alive");
	let chunkIndex = 0;
	for (const chunk of chunks) {
		const chunkDelay = require_sse_writer.calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed);
		if (chunkDelay > 0) await require_sse_writer.delay(chunkDelay, signal);
		if (signal?.aborted) return false;
		if (res.writableEnded) return true;
		res.write(`data: ${JSON.stringify(chunk)}\n\n`);
		onChunkSent?.();
		if (signal?.aborted) return false;
		chunkIndex++;
	}
	if (!res.writableEnded) res.end();
	return true;
}
async function handleGemini(req, res, raw, model, streaming, fixtures, journal, defaults, setCorsHeaders, providerKey = "gemini") {
	const { logger } = defaults;
	setCorsHeaders(res);
	let geminiReq;
	try {
		geminiReq = JSON.parse(raw);
	} catch (parseErr) {
		const detail = parseErr instanceof Error ? parseErr.message : "unknown";
		journal.add({
			method: req.method ?? "POST",
			path: req.url ?? `/v1beta/models/${model}:generateContent`,
			headers: require_helpers.flattenHeaders(req.headers),
			body: null,
			response: {
				status: 400,
				fixture: null
			}
		});
		require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
			message: `Malformed JSON body: ${detail}`,
			code: 400,
			status: "INVALID_ARGUMENT"
		} }));
		return;
	}
	const completionReq = geminiToCompletionRequest(geminiReq, model, streaming);
	completionReq._endpointType = "chat";
	completionReq._context = require_helpers.getContext(req);
	const testId = require_helpers.getTestId(req);
	const { fixture, skippedBySequenceOrTurn } = require_router.matchFixtureDiagnostic(fixtures, completionReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform, require_router.recordMatchOptions(!!defaults.record, defaults.logger));
	const path = req.url ?? `/v1beta/models/${model}:generateContent`;
	if (fixture) logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);
	else logger.debug(`No fixture matched for request`);
	if (fixture) journal.incrementFixtureMatchCount(fixture, fixtures, testId);
	if (require_chaos.applyChaos(res, fixture, defaults.chaos, req.headers, journal, {
		method: req.method ?? "POST",
		path,
		headers: require_helpers.flattenHeaders(req.headers),
		body: completionReq
	}, fixture ? "fixture" : "proxy", defaults.registry, defaults.logger)) return;
	if (!fixture) {
		if (require_helpers.resolveStrictMode(defaults.strict, req.headers)) {
			const strictMessage = require_helpers.strictNoMatchMessage(skippedBySequenceOrTurn);
			logger.error(require_helpers.strictNoMatchLogLine(req.method ?? "POST", path, skippedBySequenceOrTurn));
			journal.add({
				method: req.method ?? "POST",
				path,
				headers: require_helpers.flattenHeaders(req.headers),
				body: completionReq,
				response: {
					status: 503,
					fixture: null,
					...require_helpers.strictOverrideField(defaults.strict, req.headers)
				}
			});
			require_sse_writer.writeErrorResponse(res, 503, JSON.stringify({ error: {
				message: strictMessage,
				code: 503,
				status: "UNAVAILABLE"
			} }));
			return;
		}
		if (defaults.record) {
			const outcome = await require_recorder.proxyAndRecord(req, res, completionReq, providerKey, path, fixtures, defaults, raw);
			if (outcome === "handled_by_hook") return;
			if (outcome !== "not_configured") {
				journal.add({
					method: req.method ?? "POST",
					path,
					headers: require_helpers.flattenHeaders(req.headers),
					body: completionReq,
					response: {
						status: res.statusCode ?? 200,
						fixture: null,
						source: "proxy"
					}
				});
				return;
			}
		}
		journal.add({
			method: req.method ?? "POST",
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: completionReq,
			response: {
				status: 404,
				fixture: null,
				...require_helpers.strictOverrideField(defaults.strict, req.headers)
			}
		});
		require_sse_writer.writeErrorResponse(res, 404, JSON.stringify({ error: {
			message: "No fixture matched",
			code: 404,
			status: "NOT_FOUND"
		} }));
		return;
	}
	const response = await require_helpers.resolveResponse(fixture, completionReq);
	const latency = fixture.latency ?? defaults.latency;
	const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);
	const replaySpeed = fixture.replaySpeed ?? defaults.replaySpeed;
	if (require_helpers.isErrorResponse(response)) {
		const status = response.status ?? 500;
		journal.add({
			method: req.method ?? "POST",
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: completionReq,
			response: {
				status,
				fixture
			}
		});
		const geminiError = { error: {
			code: status,
			message: response.error.message,
			status: response.error.type ?? "ERROR"
		} };
		require_sse_writer.writeErrorResponse(res, status, JSON.stringify(geminiError), { retryAfter: response.retryAfter });
		return;
	}
	if (require_helpers.isAudioResponse(response)) {
		const effectiveStrict = require_helpers.resolveStrictMode(defaults.strict, req.headers);
		const effReasoning = require_helpers.resolveReasoningForModel(response.reasoning, model, effectiveStrict, defaults.logger);
		const journalEntry = journal.add({
			method: req.method ?? "POST",
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: completionReq,
			response: {
				status: 200,
				fixture
			}
		});
		if (!streaming) {
			const body = buildGeminiAudioResponse(response, logger, effReasoning);
			res.writeHead(200, { "Content-Type": "application/json" });
			res.end(JSON.stringify(body));
		} else {
			const chunks = buildGeminiAudioStreamChunks(response, logger, effReasoning);
			const interruption = require_interruption.createInterruptionSignal(fixture);
			if (!await writeGeminiSSEStream(res, chunks, {
				latency,
				streamingProfile: fixture.streamingProfile,
				recordedTimings: fixture.recordedTimings,
				replaySpeed,
				signal: interruption?.signal,
				onChunkSent: interruption?.tick
			})) {
				if (!res.writableEnded) res.destroy();
				journalEntry.response.interrupted = true;
				journalEntry.response.interruptReason = interruption?.reason();
			}
			interruption?.cleanup();
		}
		return;
	}
	if (require_helpers.isContentWithToolCallsResponse(response)) {
		if (response.webSearches?.length) logger.warn("webSearches in fixture response are not supported for Gemini API — ignoring");
		const overrides = require_helpers.extractOverrides(response);
		const effectiveStrict = require_helpers.resolveStrictMode(defaults.strict, req.headers);
		const effReasoning = require_helpers.resolveReasoningForModel(response.reasoning, model, effectiveStrict, defaults.logger);
		const journalEntry = journal.add({
			method: req.method ?? "POST",
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: completionReq,
			response: {
				status: 200,
				fixture
			}
		});
		if (!streaming) {
			const body = buildGeminiContentWithToolCallsResponse(response.content ?? "", response.toolCalls ?? [], logger, effReasoning, overrides, response.blocks);
			res.writeHead(200, { "Content-Type": "application/json" });
			res.end(JSON.stringify(body));
		} else {
			const chunks = buildGeminiContentWithToolCallsStreamChunks(response.content ?? "", response.toolCalls ?? [], chunkSize, logger, effReasoning, overrides, response.blocks);
			const interruption = require_interruption.createInterruptionSignal(fixture);
			if (!await writeGeminiSSEStream(res, chunks, {
				latency,
				streamingProfile: fixture.streamingProfile,
				recordedTimings: fixture.recordedTimings,
				replaySpeed,
				signal: interruption?.signal,
				onChunkSent: interruption?.tick
			})) {
				if (!res.writableEnded) res.destroy();
				journalEntry.response.interrupted = true;
				journalEntry.response.interruptReason = interruption?.reason();
			}
			interruption?.cleanup();
		}
		return;
	}
	if (require_helpers.isTextResponse(response)) {
		if (response.webSearches?.length) logger.warn("webSearches in fixture response are not supported for Gemini API — ignoring");
		const overrides = require_helpers.extractOverrides(response);
		const effectiveStrict = require_helpers.resolveStrictMode(defaults.strict, req.headers);
		const effReasoning = require_helpers.resolveReasoningForModel(response.reasoning, model, effectiveStrict, defaults.logger);
		const journalEntry = journal.add({
			method: req.method ?? "POST",
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: completionReq,
			response: {
				status: 200,
				fixture
			}
		});
		if (!streaming) {
			const body = buildGeminiTextResponse(response.content, effReasoning, overrides);
			res.writeHead(200, { "Content-Type": "application/json" });
			res.end(JSON.stringify(body));
		} else {
			const chunks = buildGeminiTextStreamChunks(response.content, chunkSize, effReasoning, overrides);
			const interruption = require_interruption.createInterruptionSignal(fixture);
			if (!await writeGeminiSSEStream(res, chunks, {
				latency,
				streamingProfile: fixture.streamingProfile,
				recordedTimings: fixture.recordedTimings,
				replaySpeed,
				signal: interruption?.signal,
				onChunkSent: interruption?.tick
			})) {
				if (!res.writableEnded) res.destroy();
				journalEntry.response.interrupted = true;
				journalEntry.response.interruptReason = interruption?.reason();
			}
			interruption?.cleanup();
		}
		return;
	}
	if (require_helpers.isToolCallResponse(response)) {
		if (response.webSearches?.length) logger.warn("webSearches in fixture response are not supported for Gemini API — ignoring");
		const overrides = require_helpers.extractOverrides(response);
		const effectiveStrict = require_helpers.resolveStrictMode(defaults.strict, req.headers);
		const effReasoning = require_helpers.resolveReasoningForModel(response.reasoning, model, effectiveStrict, defaults.logger);
		const journalEntry = journal.add({
			method: req.method ?? "POST",
			path,
			headers: require_helpers.flattenHeaders(req.headers),
			body: completionReq,
			response: {
				status: 200,
				fixture
			}
		});
		if (!streaming) {
			const body = buildGeminiToolCallResponse(response.toolCalls, logger, effReasoning, overrides);
			res.writeHead(200, { "Content-Type": "application/json" });
			res.end(JSON.stringify(body));
		} else {
			const chunks = buildGeminiToolCallStreamChunks(response.toolCalls, chunkSize, logger, effReasoning, overrides);
			const interruption = require_interruption.createInterruptionSignal(fixture);
			if (!await writeGeminiSSEStream(res, chunks, {
				latency,
				streamingProfile: fixture.streamingProfile,
				recordedTimings: fixture.recordedTimings,
				replaySpeed,
				signal: interruption?.signal,
				onChunkSent: interruption?.tick
			})) {
				if (!res.writableEnded) res.destroy();
				journalEntry.response.interrupted = true;
				journalEntry.response.interruptReason = interruption?.reason();
			}
			interruption?.cleanup();
		}
		return;
	}
	journal.add({
		method: req.method ?? "POST",
		path,
		headers: require_helpers.flattenHeaders(req.headers),
		body: completionReq,
		response: {
			status: 500,
			fixture
		}
	});
	require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
		message: "Fixture response did not match any known type",
		code: 500,
		status: "INTERNAL"
	} }));
}

//#endregion
exports.handleGemini = handleGemini;
//# sourceMappingURL=gemini.cjs.map