import { LAB_REPRESENTATIVE_AGENT } from "../../agents/identity.js";
import { createId, nowIso } from "../../shared/index.js";
import { readLabMeetingState } from "../lab-meeting/index.js";
import { getRun } from "../run-state/index.js";
import { listSubplans } from "../subplan/index.js";
import { listTeamInbox, listTeamTasks, loadTeamRuntime } from "../team-mode/index.js";
import { readOrchestratorEvents } from "./store.js";
export async function buildOrchestratorState(store, runId) {
    const run = await getRun(store, runId);
    if (!run)
        throw new Error(`SEED run not found: ${runId}`);
    const [events, meeting, runtime, subplans] = await Promise.all([
        readOrchestratorEvents(store, runId),
        readLabMeetingState(store, runId),
        loadTeamRuntime(store, runId),
        listSubplans(store, runId),
    ]);
    const teamTasks = runtime ? await listTeamTasks(store, runId) : [];
    const labRepresentative = runtime?.members.find((member) => member.role === "lead")?.name ?? LAB_REPRESENTATIVE_AGENT;
    const leadInbox = runtime ? await listTeamInbox(store, runId, String(labRepresentative), { includeAcknowledged: false }) : [];
    const openSubplans = subplans.filter((subplan) => subplan.status !== "accepted" && subplan.status !== "cancelled");
    const blockedTeamTask = teamTasks.find((task) => task.status === "blocked");
    const reviewTeamTask = teamTasks.find((task) => task.status === "review");
    const verifyingSubplan = openSubplans.find((subplan) => subplan.status === "verifying");
    const blockedSubplan = openSubplans.find((subplan) => subplan.status === "blocked" || subplan.status === "rework");
    const executableSubplan = openSubplans.find((subplan) => ["planned", "ready", "executing"].includes(subplan.status));
    return {
        run_id: runId,
        generated_at: nowIso(),
        latest_event: events.at(-1),
        recent_events: events.slice(-12),
        next_action: (run.status === "awaiting_feedback" || meeting?.status === "awaiting_feedback"
            ? action("wait_for_professor", 100, "Wait for professor feedback before dispatching more internal work.", {
                reason: "Lab Meeting or run state is awaiting professor feedback.",
                suggested_tool: "normal professor chat feedback",
                related_id: meeting?.current_meeting_id,
            })
            : leadInbox.length > 0
                ? action("read_team_inbox", 90, `Read ${leadInbox.length} unread message(s) for ${labRepresentative}.`, {
                    reason: "Worker output should be reviewed before dispatching the next step.",
                    suggested_tool: "seed_team_inbox",
                    suggested_args: { member: labRepresentative },
                    related_id: String(labRepresentative),
                })
                : reviewTeamTask
                    ? action("review_member_output", 80, `Review team task ${reviewTeamTask.team_task_id}: ${reviewTeamTask.title}`, {
                        reason: "A team task is ready for Lab-Representative review.",
                        suggested_tool: "seed_team_task_update",
                        related_id: reviewTeamTask.team_task_id,
                    })
                    : blockedTeamTask
                        ? action("resolve_blocker", 75, `Resolve blocked team task ${blockedTeamTask.team_task_id}: ${blockedTeamTask.title}`, {
                            reason: blockedTeamTask.blocker ?? "Team task is blocked.",
                            suggested_tool: "seed_team_meeting_create",
                            related_id: blockedTeamTask.team_task_id,
                        })
                        : verifyingSubplan
                            ? action("verify_subplan", 70, `Verify sub-plan ${verifyingSubplan.subplan_id}: ${verifyingSubplan.title}`, {
                                reason: "A sub-plan is in verifying state and needs an accepted/rework/blocked verdict.",
                                suggested_tool: "seed_subplan_verify",
                                suggested_args: { subplan_id: verifyingSubplan.subplan_id },
                                related_id: verifyingSubplan.subplan_id,
                            })
                            : blockedSubplan
                                ? action("resolve_blocker", 65, `Resolve sub-plan ${blockedSubplan.subplan_id}: ${blockedSubplan.title}`, {
                                    reason: blockedSubplan.latest_verdict?.summary ?? `Sub-plan is ${blockedSubplan.status}.`,
                                    suggested_tool: "seed_team_meeting_create",
                                    related_id: blockedSubplan.subplan_id,
                                })
                                : executableSubplan
                                    ? action("advance_subplan", 60, `Advance sub-plan ${executableSubplan.subplan_id}: ${executableSubplan.title}`, {
                                        reason: `Sub-plan is ${executableSubplan.status}; continue its plan-execute-verify lifecycle.`,
                                        suggested_tool: "seed_subplan_transition",
                                        suggested_args: { subplan_id: executableSubplan.subplan_id },
                                        related_id: executableSubplan.subplan_id,
                                    })
                                    : action("create_subplan", 50, "Create the next required sub-plan before dispatching more work.", {
                                        reason: "No open sub-plan is available for the next plan-execute-verify unit.",
                                        suggested_tool: "seed_subplan_create",
                                    })),
    };
}
export function renderOrchestratorContext(state) {
    return `<system-reminder>
[SEED orchestrator loop]
Next action: p${state.next_action.priority} ${state.next_action.category}${state.next_action.related_id ? ` ${state.next_action.related_id}` : ""}
Summary: ${state.next_action.summary}
Reason: ${state.next_action.reason}
Suggested tool: ${state.next_action.suggested_tool ?? "none"}
Latest loop event: ${state.latest_event ? `${state.latest_event.type}: ${state.latest_event.summary}` : "none"}

Use seed_orchestrator_record_decision after choosing the next dispatch or wait state.
</system-reminder>`;
}
function action(category, priority, summary, input) {
    return {
        action_id: createId("orch_next"),
        category,
        priority,
        summary,
        reason: input.reason,
        related_id: input.related_id,
        suggested_tool: input.suggested_tool,
        suggested_args: input.suggested_args,
    };
}
//# sourceMappingURL=engine.js.map