import { listBackgroundTasks } from "../features/background-state/index.js";
import { markLabMeetingRepresentativeReportRequested } from "../features/lab-meeting/index.js";
import { promptOpenCodeSession } from "../features/model-call/index.js";
import { appendEvent } from "../features/observability/index.js";
import { getRun } from "../features/run-state/index.js";
import { sendSeedBackgroundFollowup } from "../tools/registry.js";
export async function requestBackgroundCompletionFromActiveBackgrounds(ctx, store, runId, input) {
    const active = (await listBackgroundTasks(store, runId)).filter(isActiveBackgroundTask);
    if (!active.length)
        return { total: 0, sent: 0, recordedOnly: 0, blocked: 0, failed: 0, targets: [] };
    const message = [
        "[SEED Lab Meeting wrap-up requested]",
        `Meeting: ${input.meetingId ?? "(pending)"}`,
        "",
        "Finish the background mission that is already assigned to this session. Do not start a new subtask, new file edit, or new delegation.",
        "Record a concise checkpoint/report with what changed, what evidence exists, blockers, and the next proposed step.",
        "Then wait for Lab-Representative/professor feedback before continuing.",
    ].join("\n");
    let sent = 0;
    let recordedOnly = 0;
    let blocked = 0;
    let failed = 0;
    const targets = [];
    for (const task of active) {
        targets.push(`${task.background_id}:${task.target_agent ?? task.kind}`);
        try {
            const result = await sendSeedBackgroundFollowup(store, { directory: ctx.directory, client: ctx.client, worktree: ctx.worktree }, {
                run_id: runId,
                background_id: task.background_id,
                message,
                actor: "lab-representative",
                session_id: input.sessionId,
            });
            const status = String(result.status ?? "unknown");
            if (status === "sent")
                sent += 1;
            else if (status === "recorded_only")
                recordedOnly += 1;
            else if (status === "blocked")
                blocked += 1;
            else
                failed += 1;
        }
        catch (error) {
            failed += 1;
            await appendEvent(store, runId, {
                type: "lab_meeting_wrap_up_followup_failed",
                actor: "lab-representative",
                session_id: input.sessionId,
                summary: `${task.background_id}: Lab Meeting background-completion follow-up failed`,
                metadata: {
                    background_id: task.background_id,
                    target_agent: task.target_agent,
                    child_session_id: task.session_id,
                    error: error instanceof Error ? error.message : String(error),
                },
            });
        }
    }
    await appendEvent(store, runId, {
        type: "lab_meeting_wrap_up_followups_requested",
        actor: "lab-representative",
        session_id: input.sessionId,
        summary: `Requested background-completion checkpoint from ${active.length} active background task(s).`,
        metadata: {
            meeting_id: input.meetingId,
            sent,
            recorded_only: recordedOnly,
            blocked,
            failed,
            targets,
        },
    });
    return { total: active.length, sent, recordedOnly, blocked, failed, targets };
}
export function formatLabMeetingBackgroundCompletionFollowup(input) {
    if (input.total === 0)
        return "Background completion follow-up: no active background workers.";
    return `Background completion follow-up:
- active workers: ${input.total}
- live prompts sent: ${input.sent}
- trace-only records: ${input.recordedOnly}
- blocked: ${input.blocked}
- failed: ${input.failed}
- targets: ${input.targets.join(", ")}`;
}
export async function requestLabRepresentativeMeetingReport(ctx, store, runId, input = {}) {
    const run = await getRun(store, runId);
    const sessionId = input.sessionId ?? run?.root_session_id;
    if (!run)
        return { status: "skipped", reason: "run not found" };
    if (!sessionId)
        return { status: "skipped", reason: "root Lab-Representative session is unknown" };
    const marked = await markLabMeetingRepresentativeReportRequested(store, runId);
    if (!marked.changed) {
        return { status: "skipped", session_id: sessionId, reason: "Lab-Representative report already requested for this meeting" };
    }
    const body = {
        agent: run.active_agent || "lab-representative",
        parts: [
            {
                type: "text",
                text: [
                    "[SEED Lab Meeting opened]",
                    "The professor manually opened /seed-lab-meeting.",
                    "",
                    "The SEED framework has paused new queue/delegation/write work and is awaiting professor feedback.",
                    "Do not start new work. Summarize only what is already completed or checkpointed.",
                    "",
                    "Report to the professor:",
                    "- current implementation/results",
                    "- active or completed agent-threads and background completion checkpoints",
                    "- evidence and artifact paths",
                    "- blockers or risks",
                    "- proposed next plan after professor feedback",
                    "",
                    `Meeting summary artifact: ${marked.state?.current_meeting_ref ?? "(pending)"}`,
                    "Stop after the report and wait for the professor's normal chat feedback.",
                ].join("\n"),
                metadata: {
                    seed_mode: "lab_meeting_report",
                    seed_run_id: runId,
                    seed_source: input.source ?? "manual",
                    seed_meeting_id: marked.state?.current_meeting_id,
                },
            },
        ],
    };
    try {
        await promptOpenCodeSession(ctx, sessionId, body, ctx.directory, true);
        await appendEvent(store, runId, {
            type: "lab_meeting_representative_report_requested",
            actor: "seed-framework",
            session_id: sessionId,
            summary: "Requested Lab-Representative professor-facing Lab Meeting report.",
            metadata: {
                source: input.source ?? "manual",
                meeting_id: marked.state?.current_meeting_id,
                meeting_ref: marked.state?.current_meeting_ref,
            },
        });
        return { status: "sent", session_id: sessionId };
    }
    catch (error) {
        await appendEvent(store, runId, {
            type: "lab_meeting_representative_report_failed",
            actor: "seed-framework",
            session_id: sessionId,
            summary: error instanceof Error ? error.message.slice(0, 240) : String(error).slice(0, 240),
            metadata: {
                source: input.source ?? "manual",
                meeting_id: marked.state?.current_meeting_id,
            },
        });
        return { status: "failed", session_id: sessionId, reason: error instanceof Error ? error.message : String(error) };
    }
}
function isActiveBackgroundTask(task) {
    return task.status === "running";
}
//# sourceMappingURL=lab-meeting-control.js.map