import { HUB_DEFAULT_AGENT_ID } from "../../constants.js";
export function createRemoteInteractiveView(app, ui, options) {
    const session = app.selectedAgent ? mapAgentSession(app.selectedAgent) : undefined;
    const live = mapLive(app.live);
    const footer = createFooterView(session, live, app.peers.length, options.peerId, options.cwd, app.welcome?.sessionId, resolveBoundAgentId(app, options.helloAgentId));
    const status = createStatusView(ui, session, live);
    const agents = app.view && Array.isArray(app.view.agentOrder) && app.view.agentsById
        ? filterScopedAgentIds(app.view.agentOrder, app.view.agentsById, app.welcome?.scopeRootAgentId)
            .map((agentId) => {
            const agent = app.view?.agentsById[agentId];
            if (!agent) {
                return undefined;
            }
            return {
                id: agentId,
                parentId: agent.parentId,
                kind: agent.kind,
                lifecycle: agent.lifecycle,
                name: agent.name,
                summary: agent.summary,
                isRunning: agent.status.isRunning,
                messageCount: agent.messageCount ?? agent.items.filter((item) => item.type === "message").length,
                model: agent.context.model,
            };
        })
            .filter((agent) => agent !== undefined)
        : [];
    return {
        connection: {
            state: ui.connectionState,
            message: ui.connectionMessage,
        },
        welcome: app.welcome,
        session,
        live,
        agents,
        peers: app.peers,
        footer,
        status,
        commands: options.visibleCommands,
    };
}
function resolveBoundAgentId(app, helloAgentId) {
    const fromWelcome = app.welcome?.agentId;
    if (fromWelcome !== undefined && fromWelcome !== "") {
        return fromWelcome;
    }
    if (typeof helloAgentId === "string" && helloAgentId.trim() !== "") {
        return helloAgentId.trim();
    }
    return HUB_DEFAULT_AGENT_ID;
}
function filterScopedAgentIds(agentIds, agentsById, scopeRootAgentId) {
    if (!scopeRootAgentId || scopeRootAgentId === HUB_DEFAULT_AGENT_ID) {
        return [...agentIds];
    }
    return agentIds.filter((agentId) => isAgentInScope(agentId, scopeRootAgentId, agentsById));
}
function isAgentInScope(agentId, scopeRootAgentId, agentsById) {
    let currentId = agentId;
    const seen = new Set();
    while (currentId && !seen.has(currentId)) {
        if (currentId === scopeRootAgentId) {
            return true;
        }
        seen.add(currentId);
        currentId = agentsById[currentId]?.parentId;
    }
    return false;
}
function mapAgentSession(agent) {
    return {
        sessionId: agent.sessionId,
        cwd: agent.cwd,
        protocolVersion: agent.protocolVersion,
        sessionFile: agent.sessionFile ?? "",
        items: agent.items.map((item) => ({ ...item })),
        availableModels: [...agent.availableModels],
        availableThinkingLevels: [...agent.availableThinkingLevels],
        isRunning: agent.status.isRunning,
        pendingToolCallIds: [...agent.context.pendingToolCallIds],
        queuedMessages: [...agent.queue.messages],
        steeringMessages: [...(agent.queue.steering ?? [])],
        followUpMessages: [...(agent.queue.followUp ?? [])],
        model: agent.context.model,
        thinkingLevel: agent.context.thinkingLevel,
        autoCompactionEnabled: agent.context.autoCompactionEnabled ?? true,
        contextUsage: agent.context.contextUsage,
        sessionName: agent.sessionName,
        lastError: agent.lastError,
        diagnostics: [...agent.diagnostics],
        runStartedAt: agent.status.runStartedAt,
        lastRunStartedAt: agent.status.lastRunStartedAt,
        lastRunEndedAt: agent.status.lastRunEndedAt,
        lastRunDurationMs: agent.status.lastRunDurationMs,
        lastRunEndReason: agent.status.lastRunEndReason,
    };
}
function mapLive(snapshot) {
    return {
        streamingMessageId: snapshot?.streamingMessageId,
        streamingMessageIndex: snapshot?.streamingMessageIndex,
        streamingMessage: snapshot?.streamingMessage,
        toolExecutions: (snapshot?.toolExecutions ?? []).map((execution) => ({
            ...execution,
            args: execution.args ? { ...execution.args } : undefined,
        })),
        statusMessage: snapshot?.statusMessage,
    };
}
function createFooterView(session, live, peerCount, peerId, cwd, sessionId, boundAgentId) {
    const steeringCount = session?.steeringMessages?.length ?? 0;
    const followUpCount = session?.followUpMessages?.length ?? 0;
    const queuedCount = session?.queuedMessages?.length ?? 0;
    const totalCount = steeringCount + followUpCount + queuedCount;
    const pendingToolCount = Math.max(session?.pendingToolCallIds.length ?? 0, live.toolExecutions.length);
    const matchedModel = session?.model
        ? session.availableModels.find((model) => model.provider === session.model?.provider && model.modelId === session.model?.modelId)
        : undefined;
    const contextWindow = session?.contextUsage?.contextWindow ?? matchedModel?.contextWindow;
    let queueSummary;
    if (steeringCount > 0) {
        queueSummary = `steer ${steeringCount}${followUpCount + queuedCount > 0 ? ` \u00b7 follow-up ${followUpCount + queuedCount}` : ""}`;
    }
    else {
        queueSummary = `queued ${totalCount}`;
    }
    return {
        cwd: session?.cwd && session.cwd.length > 0 ? session.cwd : cwd,
        modelLabel: session?.model ? `${session.model.provider}/${session.model.modelId}` : "no-model",
        queueSummary,
        pendingToolCount,
        peerCount,
        isRunning: session?.isRunning ?? false,
        peerId,
        boundAgentId,
        sessionId: session?.sessionId ?? sessionId,
        contextWindow,
        contextUsage: session?.contextUsage,
    };
}
function createStatusView(ui, session, live) {
    return {
        connectionMessage: ui.connectionState === "connected" ? undefined : ui.connectionMessage,
        diagnostics: session?.diagnostics ?? [],
        lastError: session?.lastError,
        liveStatusMessage: ui.isCancelling && session?.isRunning ? "Cancelling..." : live.statusMessage,
        crdtResyncMessage: ui.isCrdtResyncing ? "resyncing session state" : undefined,
    };
}
//# sourceMappingURL=remote-interactive-state.js.map