import { a as onKoiEvent, i as getKoiRunContext } from "./koi-events-CVGX2xkt.js";
import { t as appendEvent } from "./event-log-DMRSRkMD.js";

//#region src/sessions/koi-event-bridge.ts
/**
* Koi events should carry the real participant whenever possible. Older
* emitters only know the speaker koi id, so we preserve that as `koi:<id>`
* instead of collapsing every runtime event into the same anonymous sender.
*/
const KOI_PARTICIPANT_ID_SENTINEL = "koi";
function stringField(value, fallback = "") {
	if (typeof value === "string") return value;
	if (typeof value === "number" || typeof value === "boolean") return String(value);
	return fallback;
}
function sessionIdFor(ev) {
	return ev.sessionKey || null;
}
function traceIdFor(ev) {
	return `koi-run:${ev.runId}`;
}
function participantIdFor(ev) {
	const data = ev.data || {};
	const direct = typeof data.participantId === "string" && data.participantId.trim() ? data.participantId.trim() : typeof data.actorParticipantId === "string" && data.actorParticipantId.trim() ? data.actorParticipantId.trim() : void 0;
	if (direct) return direct;
	const speakerKoiId = getKoiRunContext(ev.runId)?.speakerKoiId;
	return speakerKoiId ? `koi:${speakerKoiId}` : KOI_PARTICIPANT_ID_SENTINEL;
}
function artifactsFromData(data) {
	if (Array.isArray(data.artifacts) && data.artifacts.length > 0) return data.artifacts;
	if (Array.isArray(data.media)) return data.media;
	return [];
}
function translate(ev) {
	const data = ev.data || {};
	if (ev.stream === "tool") {
		const phase = stringField(data.event, stringField(data.phase)).toLowerCase();
		const toolName = stringField(data.name, stringField(data.tool, "tool"));
		const toolCallId = stringField(data.toolCallId, stringField(data.id, `${toolName}-${ev.seq}`));
		const description = typeof data.description === "string" ? data.description : void 0;
		if (phase === "start" || phase === "call") {
			const items = [{
				kind: "activity",
				content: {
					activityId: `tool:${toolCallId}`,
					runId: ev.runId,
					toolCallId,
					phase: "tool",
					status: "started",
					label: `Using ${toolName}`,
					...description ? { detail: description } : {}
				},
				source: "tool"
			}, {
				kind: "tool_call",
				content: {
					toolName,
					toolCallId,
					args: data.input || data.args || {},
					...description ? { description } : {}
				},
				source: "tool"
			}];
			const artifacts = artifactsFromData(data);
			if (artifacts.length > 0) items.push({
				kind: "media",
				content: {
					runId: ev.runId,
					toolName,
					toolCallId,
					phase: "start",
					media: artifacts,
					artifacts
				},
				source: "tool"
			});
			return items;
		}
		if (phase === "update" || phase === "progress") {
			const output = typeof data.output === "string" ? data.output : typeof data.partialResult === "string" ? data.partialResult : "";
			const items = [{
				kind: "activity",
				content: {
					activityId: `tool:${toolCallId}`,
					runId: ev.runId,
					toolCallId,
					phase: "tool",
					status: "progress",
					label: `Using ${toolName}`
				},
				source: "tool"
			}, {
				kind: "tool_progress",
				content: {
					toolCallId,
					output
				},
				source: "tool"
			}];
			const artifacts = artifactsFromData(data);
			if (artifacts.length > 0) items.push({
				kind: "media",
				content: {
					runId: ev.runId,
					toolName,
					toolCallId,
					phase: "update",
					media: artifacts,
					artifacts
				},
				source: "tool"
			});
			return items;
		}
		if (phase === "result" || phase === "complete" || phase === "done") {
			const output = typeof data.output === "string" ? data.output : typeof data.result === "string" ? data.result : data.result && typeof data.result === "object" ? JSON.stringify(data.result) : "";
			const isError = data.isError === true;
			const items = [{
				kind: "activity",
				content: {
					activityId: `tool:${toolCallId}`,
					runId: ev.runId,
					toolCallId,
					phase: "tool",
					status: isError ? "failed" : "completed",
					label: `Using ${toolName}`,
					severity: isError ? "error" : "info"
				},
				source: "tool"
			}, {
				kind: "tool_result",
				content: {
					toolCallId,
					output,
					isError,
					durationMs: typeof data.durationMs === "number" ? data.durationMs : void 0
				},
				source: "tool"
			}];
			const artifacts = artifactsFromData(data);
			if (artifacts.length > 0) items.push({
				kind: "media",
				content: {
					runId: ev.runId,
					toolName,
					toolCallId,
					phase: "result",
					media: artifacts,
					artifacts
				},
				source: "tool"
			});
			return items;
		}
		return [];
	}
	if (ev.stream === "assistant") {
		const text = typeof data.text === "string" ? data.text : "";
		if (!text) return [];
		return [{
			kind: "utterance",
			content: {
				text,
				final: data.final !== false
			},
			source: "model"
		}];
	}
	if (ev.stream === "lifecycle") {
		const phase = stringField(data.event, stringField(data.phase, "lifecycle"));
		const status = phase === "end" ? "completed" : phase === "error" ? "failed" : "started";
		return [{
			kind: "activity",
			content: {
				activityId: `run:${ev.runId}`,
				runId: ev.runId,
				phase: phase === "end" ? "finalizing" : "thinking",
				status,
				label: phase === "end" ? "Finished response" : "Thinking",
				severity: status === "failed" ? "error" : "info"
			},
			source: "system"
		}, {
			kind: "system",
			content: {
				event: phase,
				data
			},
			source: "system"
		}];
	}
	if (ev.stream === "error") return [{
		kind: "system",
		content: {
			event: "error",
			data
		},
		source: "system"
	}];
	return [];
}
let unsubscribe = null;
function startKoiEventBridge() {
	if (unsubscribe) return unsubscribe;
	unsubscribe = onKoiEvent((ev) => {
		const sessionId = sessionIdFor(ev);
		if (!sessionId) return;
		const participantId = participantIdFor(ev);
		const translated = translate(ev);
		if (translated.length === 0) return;
		for (const item of translated) try {
			appendEvent({
				sessionId,
				participantId,
				kind: item.kind,
				content: item.content,
				source: item.source,
				traceId: traceIdFor(ev)
			});
		} catch (err) {
			console.warn(`[session-bridge] appendEvent failed: ${err?.message}`);
		}
	});
	return unsubscribe;
}

//#endregion
export { startKoiEventBridge };