import { appendEvent } from "../features/observability/index.js";
import { createRunStore, getActiveRun } from "../features/run-state/index.js";
import { formatLabMeetingNotice, peekLabMeetingDeadline } from "../features/lab-meeting/index.js";
import { deliverQueuedAgentMessages } from "../features/message-bus/index.js";
import { formatBackgroundNotificationReminder, listBackgroundNotifications, listBackgroundTasks, markBackgroundNotificationDelivered, markBackgroundTaskNotified, upsertBackgroundTerminalNotification, } from "../features/background-state/index.js";
export function createChatMessageHandler(ctx) {
    const store = createRunStore(ctx.input.directory, ctx.config);
    return async function chatMessageHandler(input, output) {
        const active = await getActiveRun(store);
        if (!active)
            return;
        await appendEvent(store, active.run_id, {
            type: "chat_message",
            actor: input.agent ?? "user",
            session_id: input.sessionID,
            summary: "OpenCode chat message observed",
        });
        const meeting = await peekLabMeetingDeadline(store, active.run_id);
        const awaitingLabMeetingFeedback = meeting.enabled && meeting.state?.status === "awaiting_feedback";
        if (awaitingLabMeetingFeedback && output) {
            output.parts ??= [];
            output.parts.push({
                type: "text",
                text: formatLabMeetingNotice(meeting),
                synthetic: true,
            });
        }
        const terminalTasks = (await listBackgroundTasks(store, active.run_id)).filter((task) => {
            if (task.parent_session_id && task.parent_session_id !== input.sessionID)
                return false;
            if (task.notified_at)
                return false;
            return task.status === "completed" || task.status === "failed" || task.status === "cancelled";
        });
        for (const task of terminalTasks) {
            await upsertBackgroundTerminalNotification(store, active.run_id, task);
        }
        const pendingNotifications = await listBackgroundNotifications(store, active.run_id, {
            status: "pending",
            parentSessionId: input.sessionID,
        });
        if (pendingNotifications.length && output) {
            output.parts ??= [];
            output.parts.push({
                type: "text",
                text: formatBackgroundNotificationReminder(pendingNotifications),
                synthetic: true,
            });
            const taskIds = new Set(terminalTasks.map((task) => task.background_id));
            for (const notification of pendingNotifications) {
                if (taskIds.has(notification.background_id)) {
                    await markBackgroundTaskNotified(store, active.run_id, notification.background_id);
                }
                else {
                    await markBackgroundNotificationDelivered(store, active.run_id, notification.notification_id);
                }
            }
        }
        if (!awaitingLabMeetingFeedback) {
            const delivered = await deliverQueuedAgentMessages(store, active.run_id, ctx.input, {
                parentSessionId: input.sessionID,
                maxDeliveries: 3,
            });
            if (delivered.delivered || delivered.mailbox_only || delivered.failed) {
                await appendEvent(store, active.run_id, {
                    type: "agent_message_delivery_tick",
                    actor: input.agent ?? store.config.default_run_agent,
                    session_id: input.sessionID,
                    summary: `message delivery tick delivered=${delivered.delivered} mailbox_only=${delivered.mailbox_only} failed=${delivered.failed}`,
                    metadata: delivered,
                });
            }
        }
    };
}
//# sourceMappingURL=chat-message.js.map