import { formatBackgroundTaskLine, listBackgroundTasks } from "../features/background-state/index.js";
import { renderContinuationContext, writeContinuationSnapshot } from "../features/continuation-state/index.js";
import { findAgentThreadBySession, listAgentThreadHelpers, renderAgentThreadContext } from "../features/agent-thread/index.js";
import { createRunStore, getActiveRun, getRun } from "../features/run-state/index.js";
import { buildTeamRosterSnapshot, findTeamMemberBySession, listTeamInbox, listTeamMeetings, listTeamTasks, loadTeamRuntime, renderMemberMemoryContext, renderTeamMeetingContext, renderTeamMemberContract, renderTeamRosterContext, writeMemberMemoryCheckpoint, } from "../features/team-mode/index.js";
import { planContextInjection, renderContextAttachments, upsertContextBundle } from "../features/context-ledger/index.js";
export function createSessionCompactingHandler(ctx) {
    const store = createRunStore(ctx.input.directory, ctx.config);
    return async function sessionCompactingHandler(input, output) {
        const injectContinuation = ctx.config.continuation.enabled && ctx.config.continuation.inject_on_compaction;
        if (!injectContinuation && !ctx.config.team_mode.enabled)
            return;
        const active = await getActiveRun(store);
        if (!active)
            return;
        const run = await getRun(store, active.run_id);
        if (!run || run.status === "completed" || run.status === "stopped")
            return;
        const runtime = await loadTeamRuntime(store, run.run_id);
        const thread = await findAgentThreadBySession(store, run.run_id, input.sessionID);
        const member = findTeamMemberBySession(runtime, input.sessionID) ?? (thread && runtime ? runtime.members.find((candidate) => candidate.name === thread.thread_id) : undefined);
        if (!(await sessionBelongsToRun(store, run.run_id, run.root_session_id, input.sessionID, runtime)) && !thread)
            return;
        const contextBundleRefs = [];
        const addContext = async (entry) => {
            if (!entry.text.trim())
                return;
            if (!ctx.config.context_ledger.enabled) {
                output.context.push(entry.text);
                return;
            }
            const bundle = await upsertContextBundle(store, run.run_id, {
                bundle_id: entry.id,
                category: entry.category,
                scope: entry.scope,
                title: entry.title,
                body: entry.text,
                owner_agent: entry.ownerAgent,
                owner_thread_id: entry.ownerThreadId,
                metadata: {
                    source: "session_compacting",
                    session_id: input.sessionID,
                },
            });
            contextBundleRefs.push(`context:${bundle.bundle_id}`);
        };
        if (injectContinuation) {
            const result = await writeContinuationSnapshot(store, run.run_id, {
                reason: "session_compacting",
                sessionId: input.sessionID,
                recordEvent: true,
            });
            await addContext({
                id: `compact-continuation-${run.run_id}-${input.sessionID}`,
                title: "SEED continuation context for compaction",
                category: "memory",
                scope: "run",
                text: renderContinuationContext(result.snapshot, ctx.config.continuation.context_max_chars),
            });
        }
        if (runtime) {
            const teamContext = await renderTeamRuntimeContext(store, run.run_id, runtime, member?.name);
            if (teamContext) {
                await addContext({
                    id: `compact-team-context-${run.run_id}-${input.sessionID}`,
                    title: "SEED team context for compaction",
                    category: "warm",
                    scope: "run",
                    text: teamContext,
                });
            }
            const meetingContext = renderTeamMeetingContext(await listTeamMeetings(store, run.run_id, {
                status: "open",
                participant: member ? String(member.name) : undefined,
            }), member ? String(member.name) : undefined);
            if (meetingContext) {
                await addContext({
                    id: `compact-team-meetings-${run.run_id}-${input.sessionID}`,
                    title: "SEED team meetings for compaction",
                    category: "hot",
                    scope: "meeting",
                    text: meetingContext,
                });
            }
        }
        if (runtime && member) {
            await addContext({
                id: `compact-member-contract-${run.run_id}-${member.name}`,
                title: `SEED member contract for compaction: ${member.name}`,
                category: "stable",
                scope: "agent_thread",
                text: renderTeamMemberContract(run.run_id, runtime, member),
                ownerAgent: member.name,
                ownerThreadId: member.name,
            });
            const memory = await writeMemberMemoryCheckpoint(store, run.run_id, runtime, member, {
                sessionId: input.sessionID,
                reason: "session_compacting",
            });
            const memoryContext = renderMemberMemoryContext(memory);
            if (memoryContext) {
                await addContext({
                    id: `compact-member-memory-${run.run_id}-${member.name}`,
                    title: `SEED member memory for compaction: ${member.name}`,
                    category: "memory",
                    scope: "agent_thread",
                    text: memoryContext,
                    ownerAgent: member.name,
                    ownerThreadId: member.name,
                });
            }
            const mailboxContext = await renderTeamMailboxContext(store, run.run_id, String(member.name));
            if (mailboxContext) {
                await addContext({
                    id: `compact-team-mailbox-${run.run_id}-${member.name}`,
                    title: `SEED team mailbox for compaction: ${member.name}`,
                    category: "hot",
                    scope: "message",
                    text: mailboxContext,
                    ownerAgent: member.name,
                    ownerThreadId: member.name,
                });
            }
        }
        if (thread) {
            const [helpers, unread, tasks] = await Promise.all([
                listAgentThreadHelpers(store, run.run_id, thread.thread_id),
                listTeamInbox(store, run.run_id, thread.thread_id, { includeAcknowledged: false }),
                listTeamTasks(store, run.run_id),
            ]);
            const openTaskIds = tasks
                .filter((task) => task.owner_agent === thread.thread_id && task.status !== "completed" && task.status !== "cancelled")
                .map((task) => task.team_task_id);
            await addContext({
                id: `compact-agent-thread-${run.run_id}-${thread.thread_id}`,
                title: `SEED agent-thread context for compaction: ${thread.thread_id}`,
                category: "warm",
                scope: "agent_thread",
                text: renderAgentThreadContext({
                    thread,
                    helpers,
                    unreadMessageCount: unread.length,
                    openTaskIds,
                }),
                ownerAgent: thread.thread_id,
                ownerThreadId: thread.thread_id,
            });
        }
        const backgroundContext = await renderBackgroundRuntimeContext(store, run.run_id);
        if (backgroundContext) {
            await addContext({
                id: `compact-background-status-${run.run_id}-${input.sessionID}`,
                title: "SEED background status for compaction",
                category: "warm",
                scope: "run",
                text: backgroundContext,
            });
        }
        if (contextBundleRefs.length && ctx.config.context_ledger.enabled) {
            const plan = await planContextInjection(store, {
                turn_kind: "session_compacting",
                run_id: run.run_id,
                actor: member?.name ?? run.active_agent,
                target_agent: member?.name ?? run.active_agent,
                target_thread_id: thread?.thread_id ?? member?.name,
                bundle_ids: contextBundleRefs,
            });
            const rendered = renderContextAttachments(plan);
            if (rendered)
                output.context.push(rendered);
        }
    };
}
async function renderTeamRuntimeContext(store, runId, runtime, memberName) {
    const snapshot = await buildTeamRosterSnapshot(store, runId, runtime, memberName);
    return renderTeamRosterContext(snapshot);
}
async function renderTeamMailboxContext(store, runId, memberName) {
    const messages = await listTeamInbox(store, runId, memberName, { includeAcknowledged: false });
    if (!messages.length)
        return undefined;
    return `<system-reminder>
[SEED team mailbox]
Member: ${memberName}
Unread messages:
${messages.slice(0, 10).map((message) => `- ${message.message_id} from:${message.from} kind:${message.kind} ${message.body}`).join("\n")}

Use seed_team_ack after reading messages that are no longer actionable.
</system-reminder>`;
}
async function renderBackgroundRuntimeContext(store, runId) {
    const tasks = await listBackgroundTasks(store, runId);
    if (!tasks.length)
        return undefined;
    return `<system-reminder>
[SEED background status]
${tasks.slice(0, 10).map(formatBackgroundTaskLine).join("\n")}
</system-reminder>`;
}
async function sessionBelongsToRun(store, runId, rootSessionId, sessionId, runtime) {
    if (!rootSessionId || rootSessionId === sessionId)
        return true;
    if (findTeamMemberBySession(runtime, sessionId))
        return true;
    const backgrounds = await listBackgroundTasks(store, runId);
    return backgrounds.some((task) => task.parent_session_id === sessionId || task.session_id === sessionId);
}
//# sourceMappingURL=session-compacting.js.map