import path from "node:path";
import { appendEvent } from "../observability/index.js";
import { runDir } from "../run-state/index.js";
import { appendJsonl, createId, nowIso, readJsonl, sanitizeText } from "../../shared/index.js";
import { LAB_REPRESENTATIVE_AGENT } from "../../agents/identity.js";
import { claimIdempotencyKey, completeIdempotencyKey } from "../idempotency/index.js";
export function orchestratorLoopPath(store, runId) {
    return path.join(runDir(store, runId), "orchestrator-loop.jsonl");
}
export async function appendOrchestratorEvent(store, runId, input) {
    const actor = input.actor ?? store.config.default_run_agent ?? LAB_REPRESENTATIVE_AGENT;
    if (input.idempotency_key) {
        const claim = await claimIdempotencyKey(store, runId, {
            key: input.idempotency_key,
            scope: "orchestrator",
            action: input.type,
            actor,
            metadata: { related_id: input.related_id },
        });
        if (!claim.claimed) {
            return {
                schema_version: 1,
                event_id: claim.record.result_ref ?? claim.record.key,
                run_id: runId,
                type: input.type,
                actor,
                created_at: claim.record.updated_at,
                summary: sanitizeText(input.summary).slice(0, 1000),
                idempotency_key: claim.record.key,
                related_id: input.related_id,
                metadata: { ...(input.metadata ?? {}), deduped: true, idempotency_status: claim.record.status },
            };
        }
    }
    const event = {
        schema_version: 1,
        event_id: createId("orch"),
        run_id: runId,
        type: input.type,
        actor,
        created_at: nowIso(),
        summary: sanitizeText(input.summary).slice(0, 1000),
        idempotency_key: input.idempotency_key,
        related_id: input.related_id,
        metadata: input.metadata ?? {},
    };
    await appendJsonl(orchestratorLoopPath(store, runId), event);
    if (input.idempotency_key) {
        await completeIdempotencyKey(store, runId, input.idempotency_key, {
            result_ref: event.event_id,
            metadata: { event_id: event.event_id },
        });
    }
    await appendEvent(store, runId, {
        type: `orchestrator_${event.type}`,
        actor: event.actor,
        session_id: input.sessionId,
        summary: event.summary,
        metadata: { event_id: event.event_id, related_id: event.related_id, ...event.metadata },
    });
    return event;
}
export async function readOrchestratorEvents(store, runId) {
    return readJsonl(orchestratorLoopPath(store, runId));
}
//# sourceMappingURL=store.js.map