import { bridgeWorkerEvent } from "./inbox.js";
function findLastAssistant(messages) {
    for (let i = messages.length - 1; i >= 0; i--) {
        const m = messages[i];
        if (m?.role !== "assistant")
            continue;
        const a = m;
        const text = extractAssistantText(a.content);
        const out = {};
        if (a.stopReason !== undefined)
            out.stopReason = a.stopReason;
        if (a.errorMessage !== undefined)
            out.errorMessage = a.errorMessage;
        if (text !== undefined)
            out.text = text;
        return out;
    }
    return undefined;
}
function extractAssistantText(content) {
    if (!Array.isArray(content))
        return undefined;
    const parts = [];
    for (const c of content) {
        const o = c;
        if (o.type === "text" && typeof o.text === "string")
            parts.push(o.text);
    }
    if (parts.length === 0)
        return undefined;
    // Cap to 600 chars in the inbox payload — the supervisor LLM
    // sees this as a quick summary; if it wants more it calls
    // `orchestrate_read_worker`. Bigger payloads bloat the inbox
    // file and the supervisor's tool-result context.
    const joined = parts.join("\n");
    return joined.length > 600 ? `${joined.slice(0, 600)}…` : joined;
}
/**
 * Called from `session-registry.makeSubscribeHandler` for every
 * AgentSessionEvent on every live session. Filters for the two SDK
 * events that map to inbox items; everything else is ignored.
 */
export async function bridgeWorkerAgentEvent(meta, event) {
    const e = event;
    if (e.type === "agent_end") {
        const messages = meta.session.messages;
        const lastAssistant = findLastAssistant(messages);
        const errorMessage = meta.session.errorMessage ??
            lastAssistant?.errorMessage;
        await bridgeWorkerEvent(meta.sessionId, "worker.ended", {
            stopReason: lastAssistant?.stopReason ?? null,
            errorMessage: errorMessage ?? null,
            assistantTextPreview: lastAssistant?.text ?? null,
        });
        return;
    }
    if (e.type === "auto_retry_end" && e.success === false) {
        await bridgeWorkerEvent(meta.sessionId, "worker.auto_retry_failed", {
            attempt: e.attempt ?? null,
            maxAttempts: e.maxAttempts ?? null,
            finalError: e.finalError ?? null,
        });
        return;
    }
}
export async function bridgeWorkerAskUserQuestion(sessionId, questions, requestId) {
    await bridgeWorkerEvent(sessionId, "worker.ask_user", {
        requestId,
        questionCount: questions.length,
        // Keep the inbox payload tight — preview is the first question's
        // header so the supervisor sees enough to decide whether to read
        // the worker's transcript. Full question detail is in the
        // worker's session, fetched via orchestrate_read_worker.
        firstQuestionHeader: questions[0]?.header ?? null,
        firstQuestionText: questions[0]?.question ?? null,
    });
}
export async function bridgeWorkerProcessAlert(sessionId, info, reason) {
    await bridgeWorkerEvent(sessionId, "worker.process_alert", {
        reason,
        processId: info.id,
        name: info.name,
        pid: info.pid,
        exitCode: info.exitCode,
        success: info.success,
    });
}
export async function bridgeWorkerDeleted(sessionId, meta) {
    await bridgeWorkerEvent(sessionId, "worker.deleted", {
        wasLive: meta.wasLive,
    });
}
//# sourceMappingURL=event-bridge.js.map