import { extractTextContent } from "../context/workspace.js";
import { mapEmbeddedToolEndResult } from "./map-stream-events.js";
//#region src/agent/embedded/subscribe-session.ts
function subscribeEmbeddedSessionEvents(session, onEvent) {
	return session.subscribe((event) => {
		const base = event;
		switch (base.type) {
			case "message_update": {
				const delta = base.assistantMessageEvent;
				if (delta?.type === "text_delta" && typeof delta.delta === "string" && delta.delta) onEvent({
					type: "token",
					content: delta.delta
				});
				if (delta?.type === "thinking_delta" && typeof delta.delta === "string" && delta.delta) onEvent({
					type: "thinking",
					content: delta.delta
				});
				break;
			}
			case "message_start":
				if (base.message?.role === "assistant") onEvent({
					type: "thinking",
					status: "started"
				});
				break;
			case "message_end":
				onEvent({ type: "message_end" });
				break;
			case "tool_execution_start": {
				const t = base;
				onEvent({
					type: "tool_start",
					toolName: t.toolName,
					toolCallId: t.toolCallId,
					args: t.args ?? {}
				});
				break;
			}
			case "tool_execution_end": {
				const t = base;
				onEvent({
					type: "tool_end",
					toolName: t.toolName,
					toolCallId: t.toolCallId,
					isError: t.isError,
					result: mapEmbeddedToolEndResult(t.result)
				});
				break;
			}
			case "tool_execution_update": {
				const t = base;
				const details = extractStructuredDetails(t.partialResult);
				if (details !== void 0) onEvent({
					type: "tool_update",
					toolName: t.toolName,
					toolCallId: t.toolCallId,
					details
				});
				break;
			}
			case "agent_start":
				onEvent({
					type: "progress",
					stage: "thinking",
					message: "Thinking..."
				});
				break;
			case "agent_end":
				onEvent({
					type: "progress",
					stage: "idle",
					message: "Done"
				});
				break;
			default: break;
		}
	});
}
/**
* Pull a structured `details` payload out of an AgentToolResult-shaped
* `partialResult`. Returns undefined when the update is text-only (e.g. shell
* stdout deltas), so callers can skip emitting empty SSE updates.
*/
function extractStructuredDetails(partial) {
	if (!partial || typeof partial !== "object") return void 0;
	const rec = partial;
	if (!("details" in rec)) return void 0;
	const d = rec.details;
	if (d === null || d === void 0) return void 0;
	if (typeof d === "object") return d;
}
function lastAssistantPlainText(session) {
	const messages = session.agent.state.messages;
	for (let i = messages.length - 1; i >= 0; i--) {
		const msg = messages[i];
		if (msg.role !== "assistant") continue;
		const content = msg.content;
		if (typeof content === "string") return content;
		if (Array.isArray(content)) return extractTextContent(content);
	}
}
//#endregion
export { lastAssistantPlainText, subscribeEmbeddedSessionEvents };

//# sourceMappingURL=subscribe-session.js.map