import "./paths-C9FmTW1x.js";
import "./agent-paths-BySKyq9I.js";
import { au as logWarn } from "./agent-scope-CLn_Ws3B.js";
import "./commands-registry-DfzoWf4b.js";
import { Er as onAgentEvent, G as DEFAULT_INPUT_TIMEOUT_MS, H as DEFAULT_INPUT_IMAGE_MAX_BYTES, J as normalizeMimeList, Ja as sendJson, K as extractFileContentFromSource, Ka as resolveAgentIdForRequest, U as DEFAULT_INPUT_IMAGE_MIMES, W as DEFAULT_INPUT_MAX_REDIRECTS, Xa as writeDone, Y as resolveInputFileLimits, Ya as setSseHeaders, ft as handleGatewayPostJsonEndpoint, ht as agentCommand, mt as resolveAssistantStreamDeltaText, pt as buildAgentMessageFromConversationEntries, q as extractImageContentFromSource, qa as resolveSessionKey, wr as emitAgentEvent } from "./reply-DQfPM5ia.js";
import { d as defaultRuntime } from "./errors-Dx3S3Nrp.js";
import "./send-DI5jsj-s.js";
import "./send-Dg2_aoK-.js";
import "./github-copilot-token-BA45-q56.js";
import "./chat-envelope-D_wSv26N.js";
import "./pi-model-discovery-BftA1L--.js";
import "./dangerous-tools-C88-uuUI.js";
import "./chrome-BFIqTpDi.js";
import "./pairing-token-BFGorDQo.js";
import "./ip-D_T5zbZS.js";
import "./ws-cvQhrVP3.js";
import "./onboarding.wallet-B12p7GUZ.js";
import "./wallet-runtime-config-BlRWvEER.js";
import "./wallet-provider-registry-ax0NJo0F.js";
import "./wallet-BPiknFdt.js";
import "./wallet-approval-auth-DT-vofLs.js";
import "./reply-prefix-BRvLVE6I.js";
import "./media-ZuS0crH3.js";
import "./path-alias-guards-DivKBvV8.js";
import "./fs-safe-Cp0MI7Oo.js";
import "./runtime-bsvPuEXH.js";
import "./device-identity-DzUZ06fL.js";
import "./solana-bond-signing-CgswTuFe.js";
import "./diagnostic-Cl18V9Cy.js";
import "./federation-BrNm7xtG.js";
import "./call-s6DNIELo.js";
import "./chunk-tBRG1JLR.js";
import "./markdown-tables-DvKl7MfL.js";
import "./send-aHqtlYYi.js";
import "./fetch-guard-hWUtz61M.js";
import "./ssrf-Blf4NrHS.js";
import "./outbound-attachment-BHTb_aF7.js";
import "./fetch-BJWQWfdf.js";
import "./delivery-queue-9lp1uujZ.js";
import { t as createDefaultDeps } from "./deps-CBapZnsi.js";
import "./memory-e9aOXNx1.js";
import "./memory-search-B8y2GTeB.js";
import "./manager-DI2w66Ae.js";
import "./query-expansion-BdzehFyx.js";
import "./memory-cli-mMVfDz8Z.js";
import "./target-errors-_IirSOQ1.js";
import "./render-C2MRWrC0.js";
import "./diagnostic-session-state-89enG0Yp.js";
import "./send-B3O8oJLA.js";
import "./model-CfutahU0.js";
import "./exec-approvals-allowlist-C5bxRc7H.js";
import "./dangerous-name-matching-B2YH8EDF.js";
import "./skills-D1Qdj69-.js";
import "./node-match-BNTZ8TY5.js";
import "./system-run-command-BvFkDQae.js";
import "./channel-selection-EDP8q9uz.js";
import "./task-planner-BW6kdamv.js";
import "./trash-BiHtb5y8.js";
import "./paths-BA7z-HF9.js";
import "./send-CKgt65ud.js";
import "./resolve-route-CbII9dNc.js";
import "./pairing-store-CUPrh2Qy.js";
import "./session-cost-usage-DQSpjhkP.js";
import "./skills-clawhub-kuGAFKgL.js";
import "./config-eval-CuVkTCse.js";
import "./channel-activity-BkfQ8RFW.js";
import "./tables-apsvCDwc.js";
import "./proxy-DU7W9XSc.js";
import "./config-BKhx4paQ.js";
import "./links-BeUKckiL.js";
import "./cli-utils-DJ7Nfw8J.js";
import "./help-format-H4GNCFCs.js";
import "./progress-CDqdg8f8.js";
import "./replies-Xddrs-mt.js";
import "./skills-remote-DkdYN-8J.js";
import "./skill-commands-CxJHp3z6.js";
import "./prompt-style-Db5iJoaI.js";
import "./pairing-labels-sAC1Ty3_.js";
import { randomUUID } from "node:crypto";
import { z } from "zod";

//#region src/gateway/open-responses.schema.ts
/**
* OpenResponses API Zod Schemas
*
* Zod schemas for the OpenResponses `/v1/responses` endpoint.
* This module is isolated from gateway imports to enable future codegen and prevent drift.
*
* @see https://www.open-responses.com/
*/
const InputTextContentPartSchema = z.object({
	type: z.literal("input_text"),
	text: z.string()
}).strict();
const OutputTextContentPartSchema = z.object({
	type: z.literal("output_text"),
	text: z.string()
}).strict();
const InputImageSourceSchema = z.discriminatedUnion("type", [z.object({
	type: z.literal("url"),
	url: z.string().url()
}), z.object({
	type: z.literal("base64"),
	media_type: z.enum([
		"image/jpeg",
		"image/png",
		"image/gif",
		"image/webp"
	]),
	data: z.string().min(1)
})]);
const InputImageContentPartSchema = z.object({
	type: z.literal("input_image"),
	source: InputImageSourceSchema
}).strict();
const InputFileSourceSchema = z.discriminatedUnion("type", [z.object({
	type: z.literal("url"),
	url: z.string().url()
}), z.object({
	type: z.literal("base64"),
	media_type: z.string().min(1),
	data: z.string().min(1),
	filename: z.string().optional()
})]);
const InputFileContentPartSchema = z.object({
	type: z.literal("input_file"),
	source: InputFileSourceSchema
}).strict();
const ContentPartSchema = z.discriminatedUnion("type", [
	InputTextContentPartSchema,
	OutputTextContentPartSchema,
	InputImageContentPartSchema,
	InputFileContentPartSchema
]);
const MessageItemRoleSchema = z.enum([
	"system",
	"developer",
	"user",
	"assistant"
]);
const MessageItemSchema = z.object({
	type: z.literal("message"),
	role: MessageItemRoleSchema,
	content: z.union([z.string(), z.array(ContentPartSchema)])
}).strict();
const FunctionCallItemSchema = z.object({
	type: z.literal("function_call"),
	id: z.string().optional(),
	call_id: z.string().optional(),
	name: z.string(),
	arguments: z.string()
}).strict();
const FunctionCallOutputItemSchema = z.object({
	type: z.literal("function_call_output"),
	call_id: z.string(),
	output: z.string()
}).strict();
const ReasoningItemSchema = z.object({
	type: z.literal("reasoning"),
	content: z.string().optional(),
	encrypted_content: z.string().optional(),
	summary: z.string().optional()
}).strict();
const ItemReferenceItemSchema = z.object({
	type: z.literal("item_reference"),
	id: z.string()
}).strict();
const ItemParamSchema = z.discriminatedUnion("type", [
	MessageItemSchema,
	FunctionCallItemSchema,
	FunctionCallOutputItemSchema,
	ReasoningItemSchema,
	ItemReferenceItemSchema
]);
const FunctionToolDefinitionSchema = z.object({
	type: z.literal("function"),
	function: z.object({
		name: z.string().min(1, "Tool name cannot be empty"),
		description: z.string().optional(),
		parameters: z.record(z.string(), z.unknown()).optional()
	})
}).strict();
const ToolDefinitionSchema = FunctionToolDefinitionSchema;
const ToolChoiceSchema = z.union([
	z.literal("auto"),
	z.literal("none"),
	z.literal("required"),
	z.object({
		type: z.literal("function"),
		function: z.object({ name: z.string() })
	})
]);
const CreateResponseBodySchema = z.object({
	model: z.string(),
	input: z.union([z.string(), z.array(ItemParamSchema)]),
	instructions: z.string().optional(),
	tools: z.array(ToolDefinitionSchema).optional(),
	tool_choice: ToolChoiceSchema.optional(),
	stream: z.boolean().optional(),
	max_output_tokens: z.number().int().positive().optional(),
	max_tool_calls: z.number().int().positive().optional(),
	user: z.string().optional(),
	temperature: z.number().optional(),
	top_p: z.number().optional(),
	metadata: z.record(z.string(), z.string()).optional(),
	store: z.boolean().optional(),
	previous_response_id: z.string().optional(),
	reasoning: z.object({
		effort: z.enum([
			"low",
			"medium",
			"high"
		]).optional(),
		summary: z.enum([
			"auto",
			"concise",
			"detailed"
		]).optional()
	}).optional(),
	truncation: z.enum(["auto", "disabled"]).optional()
}).strict();
const ResponseStatusSchema = z.enum([
	"in_progress",
	"completed",
	"failed",
	"cancelled",
	"incomplete"
]);
const OutputItemSchema = z.discriminatedUnion("type", [
	z.object({
		type: z.literal("message"),
		id: z.string(),
		role: z.literal("assistant"),
		content: z.array(OutputTextContentPartSchema),
		status: z.enum(["in_progress", "completed"]).optional()
	}).strict(),
	z.object({
		type: z.literal("function_call"),
		id: z.string(),
		call_id: z.string(),
		name: z.string(),
		arguments: z.string(),
		status: z.enum(["in_progress", "completed"]).optional()
	}).strict(),
	z.object({
		type: z.literal("reasoning"),
		id: z.string(),
		content: z.string().optional(),
		summary: z.string().optional()
	}).strict()
]);
const UsageSchema = z.object({
	input_tokens: z.number().int().nonnegative(),
	output_tokens: z.number().int().nonnegative(),
	total_tokens: z.number().int().nonnegative()
});
const ResponseResourceSchema = z.object({
	id: z.string(),
	object: z.literal("response"),
	created_at: z.number().int(),
	status: ResponseStatusSchema,
	model: z.string(),
	output: z.array(OutputItemSchema),
	usage: UsageSchema,
	error: z.object({
		code: z.string(),
		message: z.string()
	}).optional()
});
const ResponseCreatedEventSchema = z.object({
	type: z.literal("response.created"),
	response: ResponseResourceSchema
});
const ResponseInProgressEventSchema = z.object({
	type: z.literal("response.in_progress"),
	response: ResponseResourceSchema
});
const ResponseCompletedEventSchema = z.object({
	type: z.literal("response.completed"),
	response: ResponseResourceSchema
});
const ResponseFailedEventSchema = z.object({
	type: z.literal("response.failed"),
	response: ResponseResourceSchema
});
const OutputItemAddedEventSchema = z.object({
	type: z.literal("response.output_item.added"),
	output_index: z.number().int().nonnegative(),
	item: OutputItemSchema
});
const OutputItemDoneEventSchema = z.object({
	type: z.literal("response.output_item.done"),
	output_index: z.number().int().nonnegative(),
	item: OutputItemSchema
});
const ContentPartAddedEventSchema = z.object({
	type: z.literal("response.content_part.added"),
	item_id: z.string(),
	output_index: z.number().int().nonnegative(),
	content_index: z.number().int().nonnegative(),
	part: OutputTextContentPartSchema
});
const ContentPartDoneEventSchema = z.object({
	type: z.literal("response.content_part.done"),
	item_id: z.string(),
	output_index: z.number().int().nonnegative(),
	content_index: z.number().int().nonnegative(),
	part: OutputTextContentPartSchema
});
const OutputTextDeltaEventSchema = z.object({
	type: z.literal("response.output_text.delta"),
	item_id: z.string(),
	output_index: z.number().int().nonnegative(),
	content_index: z.number().int().nonnegative(),
	delta: z.string()
});
const OutputTextDoneEventSchema = z.object({
	type: z.literal("response.output_text.done"),
	item_id: z.string(),
	output_index: z.number().int().nonnegative(),
	content_index: z.number().int().nonnegative(),
	text: z.string()
});

//#endregion
//#region src/gateway/openresponses-prompt.ts
function extractTextContent(content) {
	if (typeof content === "string") return content;
	return content.map((part) => {
		if (part.type === "input_text") return part.text;
		if (part.type === "output_text") return part.text;
		return "";
	}).filter(Boolean).join("\n");
}
function buildAgentPrompt(input) {
	if (typeof input === "string") return { message: input };
	const systemParts = [];
	const conversationEntries = [];
	for (const item of input) if (item.type === "message") {
		const content = extractTextContent(item.content).trim();
		if (!content) continue;
		if (item.role === "system" || item.role === "developer") {
			systemParts.push(content);
			continue;
		}
		const normalizedRole = item.role === "assistant" ? "assistant" : "user";
		const sender = normalizedRole === "assistant" ? "Assistant" : "User";
		conversationEntries.push({
			role: normalizedRole,
			entry: {
				sender,
				body: content
			}
		});
	} else if (item.type === "function_call_output") conversationEntries.push({
		role: "tool",
		entry: {
			sender: `Tool:${item.call_id}`,
			body: item.output
		}
	});
	return {
		message: buildAgentMessageFromConversationEntries(conversationEntries),
		extraSystemPrompt: systemParts.length > 0 ? systemParts.join("\n\n") : void 0
	};
}

//#endregion
//#region src/gateway/openresponses-http.ts
/**
* OpenResponses HTTP Handler
*
* Implements the OpenResponses `/v1/responses` endpoint for FasedAgent Gateway.
*
* @see https://www.open-responses.com/
*/
const DEFAULT_BODY_BYTES = 20 * 1024 * 1024;
const DEFAULT_MAX_URL_PARTS = 8;
function writeSseEvent(res, event) {
	res.write(`event: ${event.type}\n`);
	res.write(`data: ${JSON.stringify(event)}\n\n`);
}
function normalizeHostnameAllowlist(values) {
	if (!values || values.length === 0) return;
	const normalized = values.map((value) => value.trim()).filter((value) => value.length > 0);
	return normalized.length > 0 ? normalized : void 0;
}
function resolveResponsesLimits(config) {
	const files = config?.files;
	const images = config?.images;
	const fileLimits = resolveInputFileLimits(files);
	return {
		maxBodyBytes: config?.maxBodyBytes ?? DEFAULT_BODY_BYTES,
		maxUrlParts: typeof config?.maxUrlParts === "number" ? Math.max(0, Math.floor(config.maxUrlParts)) : DEFAULT_MAX_URL_PARTS,
		files: {
			...fileLimits,
			urlAllowlist: normalizeHostnameAllowlist(files?.urlAllowlist)
		},
		images: {
			allowUrl: images?.allowUrl ?? true,
			urlAllowlist: normalizeHostnameAllowlist(images?.urlAllowlist),
			allowedMimes: normalizeMimeList(images?.allowedMimes, DEFAULT_INPUT_IMAGE_MIMES),
			maxBytes: images?.maxBytes ?? DEFAULT_INPUT_IMAGE_MAX_BYTES,
			maxRedirects: images?.maxRedirects ?? DEFAULT_INPUT_MAX_REDIRECTS,
			timeoutMs: images?.timeoutMs ?? DEFAULT_INPUT_TIMEOUT_MS
		}
	};
}
function extractClientTools(body) {
	return body.tools ?? [];
}
function applyToolChoice(params) {
	const { tools, toolChoice } = params;
	if (!toolChoice) return { tools };
	if (toolChoice === "none") return { tools: [] };
	if (toolChoice === "required") {
		if (tools.length === 0) throw new Error("tool_choice=required but no tools were provided");
		return {
			tools,
			extraSystemPrompt: "You must call one of the available tools before responding."
		};
	}
	if (typeof toolChoice === "object" && toolChoice.type === "function") {
		const targetName = toolChoice.function?.name?.trim();
		if (!targetName) throw new Error("tool_choice.function.name is required");
		const matched = tools.filter((tool) => tool.function?.name === targetName);
		if (matched.length === 0) throw new Error(`tool_choice requested unknown tool: ${targetName}`);
		return {
			tools: matched,
			extraSystemPrompt: `You must call the ${targetName} tool before responding.`
		};
	}
	return { tools };
}
function resolveOpenResponsesSessionKey(params) {
	return resolveSessionKey({
		...params,
		prefix: "openresponses"
	});
}
function createEmptyUsage() {
	return {
		input_tokens: 0,
		output_tokens: 0,
		total_tokens: 0
	};
}
function toUsage(value) {
	if (!value) return createEmptyUsage();
	const input = value.input ?? 0;
	const output = value.output ?? 0;
	const cacheRead = value.cacheRead ?? 0;
	const cacheWrite = value.cacheWrite ?? 0;
	const total = value.total ?? input + output + cacheRead + cacheWrite;
	return {
		input_tokens: Math.max(0, input),
		output_tokens: Math.max(0, output),
		total_tokens: Math.max(0, total)
	};
}
function extractUsageFromResult(result) {
	const meta = result?.meta;
	return toUsage(meta && typeof meta === "object" ? meta.agentMeta?.usage : void 0);
}
function createResponseResource(params) {
	return {
		id: params.id,
		object: "response",
		created_at: Math.floor(Date.now() / 1e3),
		status: params.status,
		model: params.model,
		output: params.output,
		usage: params.usage ?? createEmptyUsage(),
		error: params.error
	};
}
function createAssistantOutputItem(params) {
	return {
		type: "message",
		id: params.id,
		role: "assistant",
		content: [{
			type: "output_text",
			text: params.text
		}],
		status: params.status
	};
}
async function runResponsesAgentCommand(params) {
	return agentCommand({
		message: params.message,
		images: params.images.length > 0 ? params.images : void 0,
		clientTools: params.clientTools.length > 0 ? params.clientTools : void 0,
		extraSystemPrompt: params.extraSystemPrompt || void 0,
		streamParams: params.streamParams ?? void 0,
		sessionKey: params.sessionKey,
		runId: params.runId,
		deliver: false,
		messageChannel: "webchat",
		bestEffortDeliver: false
	}, defaultRuntime, params.deps);
}
async function handleOpenResponsesHttpRequest(req, res, opts) {
	const limits = resolveResponsesLimits(opts.config);
	const maxBodyBytes = opts.maxBodyBytes ?? (opts.config?.maxBodyBytes ? limits.maxBodyBytes : Math.max(limits.maxBodyBytes, limits.files.maxBytes * 2, limits.images.maxBytes * 2));
	const handled = await handleGatewayPostJsonEndpoint(req, res, {
		pathname: "/v1/responses",
		auth: opts.auth,
		trustedProxies: opts.trustedProxies,
		allowRealIpFallback: opts.allowRealIpFallback,
		rateLimiter: opts.rateLimiter,
		maxBodyBytes
	});
	if (handled === false) return false;
	if (!handled) return true;
	const parseResult = CreateResponseBodySchema.safeParse(handled.body);
	if (!parseResult.success) {
		const issue = parseResult.error.issues[0];
		sendJson(res, 400, { error: {
			message: issue ? `${issue.path.join(".")}: ${issue.message}` : "Invalid request body",
			type: "invalid_request_error"
		} });
		return true;
	}
	const payload = parseResult.data;
	const stream = Boolean(payload.stream);
	const model = payload.model;
	const user = payload.user;
	let images = [];
	let fileContexts = [];
	let urlParts = 0;
	const markUrlPart = () => {
		urlParts += 1;
		if (urlParts > limits.maxUrlParts) throw new Error(`Too many URL-based input sources: ${urlParts} (limit: ${limits.maxUrlParts})`);
	};
	try {
		if (Array.isArray(payload.input)) {
			for (const item of payload.input) if (item.type === "message" && typeof item.content !== "string") for (const part of item.content) {
				if (part.type === "input_image") {
					const source = part.source;
					const sourceType = source.type === "base64" || source.type === "url" ? source.type : void 0;
					if (!sourceType) throw new Error("input_image must have 'source.url' or 'source.data'");
					if (sourceType === "url") markUrlPart();
					const image = await extractImageContentFromSource({
						type: sourceType,
						url: source.url,
						data: source.data,
						mediaType: source.media_type
					}, limits.images);
					images.push(image);
					continue;
				}
				if (part.type === "input_file") {
					const source = part.source;
					const sourceType = source.type === "base64" || source.type === "url" ? source.type : void 0;
					if (!sourceType) throw new Error("input_file must have 'source.url' or 'source.data'");
					if (sourceType === "url") markUrlPart();
					const file = await extractFileContentFromSource({
						source: {
							type: sourceType,
							url: source.url,
							data: source.data,
							mediaType: source.media_type,
							filename: source.filename
						},
						limits: limits.files
					});
					if (file.text?.trim()) fileContexts.push(`<file name="${file.filename}">\n${file.text}\n</file>`);
					else if (file.images && file.images.length > 0) fileContexts.push(`<file name="${file.filename}">[PDF content rendered to images]</file>`);
					if (file.images && file.images.length > 0) images = images.concat(file.images);
				}
			}
		}
	} catch (err) {
		logWarn(`openresponses: request parsing failed: ${String(err)}`);
		sendJson(res, 400, { error: {
			message: "invalid request",
			type: "invalid_request_error"
		} });
		return true;
	}
	const clientTools = extractClientTools(payload);
	let toolChoicePrompt;
	let resolvedClientTools = clientTools;
	try {
		const toolChoiceResult = applyToolChoice({
			tools: clientTools,
			toolChoice: payload.tool_choice
		});
		resolvedClientTools = toolChoiceResult.tools;
		toolChoicePrompt = toolChoiceResult.extraSystemPrompt;
	} catch (err) {
		logWarn(`openresponses: tool configuration failed: ${String(err)}`);
		sendJson(res, 400, { error: {
			message: "invalid tool configuration",
			type: "invalid_request_error"
		} });
		return true;
	}
	const sessionKey = resolveOpenResponsesSessionKey({
		req,
		agentId: resolveAgentIdForRequest({
			req,
			model
		}),
		user
	});
	const prompt = buildAgentPrompt(payload.input);
	const fileContext = fileContexts.length > 0 ? fileContexts.join("\n\n") : void 0;
	const toolChoiceContext = toolChoicePrompt?.trim();
	const extraSystemPrompt = [
		payload.instructions,
		prompt.extraSystemPrompt,
		toolChoiceContext,
		fileContext
	].filter(Boolean).join("\n\n");
	if (!prompt.message) {
		sendJson(res, 400, { error: {
			message: "Missing user message in `input`.",
			type: "invalid_request_error"
		} });
		return true;
	}
	const responseId = `resp_${randomUUID()}`;
	const outputItemId = `msg_${randomUUID()}`;
	const deps = createDefaultDeps();
	const streamParams = typeof payload.max_output_tokens === "number" ? { maxTokens: payload.max_output_tokens } : void 0;
	if (!stream) {
		try {
			const result = await runResponsesAgentCommand({
				message: prompt.message,
				images,
				clientTools: resolvedClientTools,
				extraSystemPrompt,
				streamParams,
				sessionKey,
				runId: responseId,
				deps
			});
			const payloads = result?.payloads;
			const usage = extractUsageFromResult(result);
			const meta = result?.meta;
			const stopReason = meta && typeof meta === "object" ? meta.stopReason : void 0;
			const pendingToolCalls = meta && typeof meta === "object" ? meta.pendingToolCalls : void 0;
			if (stopReason === "tool_calls" && pendingToolCalls && pendingToolCalls.length > 0) {
				const functionCall = pendingToolCalls[0];
				sendJson(res, 200, createResponseResource({
					id: responseId,
					model,
					status: "incomplete",
					output: [{
						type: "function_call",
						id: `call_${randomUUID()}`,
						call_id: functionCall.id,
						name: functionCall.name,
						arguments: functionCall.arguments
					}],
					usage
				}));
				return true;
			}
			sendJson(res, 200, createResponseResource({
				id: responseId,
				model,
				status: "completed",
				output: [createAssistantOutputItem({
					id: outputItemId,
					text: Array.isArray(payloads) && payloads.length > 0 ? payloads.map((p) => typeof p.text === "string" ? p.text : "").filter(Boolean).join("\n\n") : "No response from FasedAgent.",
					status: "completed"
				})],
				usage
			}));
		} catch (err) {
			logWarn(`openresponses: non-stream response failed: ${String(err)}`);
			sendJson(res, 500, createResponseResource({
				id: responseId,
				model,
				status: "failed",
				output: [],
				error: {
					code: "api_error",
					message: "internal error"
				}
			}));
		}
		return true;
	}
	setSseHeaders(res);
	let accumulatedText = "";
	let sawAssistantDelta = false;
	let closed = false;
	let unsubscribe = () => {};
	let finalUsage;
	let finalizeRequested = null;
	const maybeFinalize = () => {
		if (closed) return;
		if (!finalizeRequested) return;
		if (!finalUsage) return;
		const usage = finalUsage;
		closed = true;
		unsubscribe();
		writeSseEvent(res, {
			type: "response.output_text.done",
			item_id: outputItemId,
			output_index: 0,
			content_index: 0,
			text: finalizeRequested.text
		});
		writeSseEvent(res, {
			type: "response.content_part.done",
			item_id: outputItemId,
			output_index: 0,
			content_index: 0,
			part: {
				type: "output_text",
				text: finalizeRequested.text
			}
		});
		const completedItem = createAssistantOutputItem({
			id: outputItemId,
			text: finalizeRequested.text,
			status: "completed"
		});
		writeSseEvent(res, {
			type: "response.output_item.done",
			output_index: 0,
			item: completedItem
		});
		writeSseEvent(res, {
			type: "response.completed",
			response: createResponseResource({
				id: responseId,
				model,
				status: finalizeRequested.status,
				output: [completedItem],
				usage
			})
		});
		writeDone(res);
		res.end();
	};
	const requestFinalize = (status, text) => {
		if (finalizeRequested) return;
		finalizeRequested = {
			status,
			text
		};
		maybeFinalize();
	};
	const initialResponse = createResponseResource({
		id: responseId,
		model,
		status: "in_progress",
		output: []
	});
	writeSseEvent(res, {
		type: "response.created",
		response: initialResponse
	});
	writeSseEvent(res, {
		type: "response.in_progress",
		response: initialResponse
	});
	writeSseEvent(res, {
		type: "response.output_item.added",
		output_index: 0,
		item: createAssistantOutputItem({
			id: outputItemId,
			text: "",
			status: "in_progress"
		})
	});
	writeSseEvent(res, {
		type: "response.content_part.added",
		item_id: outputItemId,
		output_index: 0,
		content_index: 0,
		part: {
			type: "output_text",
			text: ""
		}
	});
	unsubscribe = onAgentEvent((evt) => {
		if (evt.runId !== responseId) return;
		if (closed) return;
		if (evt.stream === "assistant") {
			const content = resolveAssistantStreamDeltaText(evt);
			if (!content) return;
			sawAssistantDelta = true;
			accumulatedText += content;
			writeSseEvent(res, {
				type: "response.output_text.delta",
				item_id: outputItemId,
				output_index: 0,
				content_index: 0,
				delta: content
			});
			return;
		}
		if (evt.stream === "lifecycle") {
			const phase = evt.data?.phase;
			if (phase === "end" || phase === "error") requestFinalize(phase === "error" ? "failed" : "completed", accumulatedText || "No response from FasedAgent.");
		}
	});
	req.on("close", () => {
		closed = true;
		unsubscribe();
	});
	(async () => {
		try {
			const result = await runResponsesAgentCommand({
				message: prompt.message,
				images,
				clientTools: resolvedClientTools,
				extraSystemPrompt,
				streamParams,
				sessionKey,
				runId: responseId,
				deps
			});
			finalUsage = extractUsageFromResult(result);
			maybeFinalize();
			if (closed) return;
			if (!sawAssistantDelta) {
				const resultAny = result;
				const payloads = resultAny.payloads;
				const meta = resultAny.meta;
				const stopReason = meta && typeof meta === "object" ? meta.stopReason : void 0;
				const pendingToolCalls = meta && typeof meta === "object" ? meta.pendingToolCalls : void 0;
				if (stopReason === "tool_calls" && pendingToolCalls && pendingToolCalls.length > 0) {
					const functionCall = pendingToolCalls[0];
					const usage = finalUsage ?? createEmptyUsage();
					writeSseEvent(res, {
						type: "response.output_text.done",
						item_id: outputItemId,
						output_index: 0,
						content_index: 0,
						text: ""
					});
					writeSseEvent(res, {
						type: "response.content_part.done",
						item_id: outputItemId,
						output_index: 0,
						content_index: 0,
						part: {
							type: "output_text",
							text: ""
						}
					});
					const completedItem = createAssistantOutputItem({
						id: outputItemId,
						text: "",
						status: "completed"
					});
					writeSseEvent(res, {
						type: "response.output_item.done",
						output_index: 0,
						item: completedItem
					});
					const functionCallItem = {
						type: "function_call",
						id: `call_${randomUUID()}`,
						call_id: functionCall.id,
						name: functionCall.name,
						arguments: functionCall.arguments
					};
					writeSseEvent(res, {
						type: "response.output_item.added",
						output_index: 1,
						item: functionCallItem
					});
					writeSseEvent(res, {
						type: "response.output_item.done",
						output_index: 1,
						item: {
							...functionCallItem,
							status: "completed"
						}
					});
					const incompleteResponse = createResponseResource({
						id: responseId,
						model,
						status: "incomplete",
						output: [completedItem, functionCallItem],
						usage
					});
					closed = true;
					unsubscribe();
					writeSseEvent(res, {
						type: "response.completed",
						response: incompleteResponse
					});
					writeDone(res);
					res.end();
					return;
				}
				const content = Array.isArray(payloads) && payloads.length > 0 ? payloads.map((p) => typeof p.text === "string" ? p.text : "").filter(Boolean).join("\n\n") : "No response from FasedAgent.";
				accumulatedText = content;
				sawAssistantDelta = true;
				writeSseEvent(res, {
					type: "response.output_text.delta",
					item_id: outputItemId,
					output_index: 0,
					content_index: 0,
					delta: content
				});
			}
		} catch (err) {
			logWarn(`openresponses: streaming response failed: ${String(err)}`);
			if (closed) return;
			finalUsage = finalUsage ?? createEmptyUsage();
			writeSseEvent(res, {
				type: "response.failed",
				response: createResponseResource({
					id: responseId,
					model,
					status: "failed",
					output: [],
					error: {
						code: "api_error",
						message: "internal error"
					},
					usage: finalUsage
				})
			});
			emitAgentEvent({
				runId: responseId,
				stream: "lifecycle",
				data: { phase: "error" }
			});
		} finally {
			if (!closed) emitAgentEvent({
				runId: responseId,
				stream: "lifecycle",
				data: { phase: "end" }
			});
		}
	})();
	return true;
}

//#endregion
export { handleOpenResponsesHttpRequest };