//#region src/session/client-history.ts
function flattenMessageContent(content) {
	if (typeof content === "string") return content;
	if (!Array.isArray(content)) return "";
	const parts = [];
	for (const block of content) {
		if (typeof block !== "object" || block === null) continue;
		const b = block;
		if (b.type === "text" && typeof b.text === "string") parts.push(b.text);
	}
	return parts.join("");
}
function parseTimestamp(ts) {
	if (!ts) return void 0;
	const ms = Date.parse(ts);
	return Number.isFinite(ms) ? ms : void 0;
}
function safeJsonParseArguments(raw) {
	const t = raw.trim();
	if (!t) return void 0;
	try {
		return JSON.parse(t);
	} catch {
		return raw;
	}
}
function collectToolResults(messages) {
	const map = /* @__PURE__ */ new Map();
	for (const m of messages) {
		if (m.role !== "tool" && m.role !== "toolResult") continue;
		const id = m.tool_call_id;
		if (!id || typeof id !== "string") continue;
		map.set(id, {
			text: flattenMessageContent(m.content),
			isError: m.isError
		});
	}
	return map;
}
function toolCallsWithResults(tool_calls, results) {
	if (!tool_calls?.length) return void 0;
	const out = [];
	for (const tc of tool_calls) {
		const res = results.get(tc.id);
		out.push({
			name: tc.function.name,
			args: safeJsonParseArguments(tc.function.arguments),
			result: res?.text,
			isError: res?.isError
		});
	}
	return out.length ? out : void 0;
}
/**
* Maps gateway/session API messages into a linear chat history for clients.
* Tool / toolResult rows are merged into assistant `toolCalls` when ids match; otherwise skipped.
*/
function messagesToClientHistory(messages, opts) {
	const slice = opts?.limit !== void 0 && messages.length > opts.limit ? messages.slice(-opts.limit) : messages;
	const results = collectToolResults(slice);
	const out = [];
	for (const m of slice) {
		if (m.role === "tool" || m.role === "toolResult") continue;
		if (m.role === "user" || m.role === "system") {
			const text = flattenMessageContent(m.content);
			out.push({
				role: m.role,
				content: text,
				timestamp: parseTimestamp(m.timestamp)
			});
			continue;
		}
		if (m.role === "assistant") {
			const text = flattenMessageContent(m.content);
			const toolCalls = toolCallsWithResults(m.tool_calls, results);
			out.push({
				role: "assistant",
				content: text,
				timestamp: parseTimestamp(m.timestamp),
				toolCalls
			});
		}
	}
	return out;
}
//#endregion
export { flattenMessageContent, messagesToClientHistory };

//# sourceMappingURL=client-history.js.map