/**
 * Handler for agent_sessions_list messages.
 * Returns OpenCode sessions for a project by querying the OpenCode API.
 *
 * Per PRD: Host filters session list responses - only returns sessions
 * where session.directory matches a registered project's absolute path.
 */
import { ErrorCode } from "@pocketcoder/shared/constants";
import { getProject } from "../db/repositories/projects.js";
import { proxyToOpenCode } from "../opencode/proxy.js";
import { filterAndSortSessions } from "../opencode/session-filter.js";
import { logger } from "../utils/logger.js";
export async function handleAgentSessionsList(message, send) {
    const msg = message;
    const { requestId, sessionId } = msg;
    const project = getProject(sessionId);
    if (!project) {
        send({
            type: "agent_sessions_list_response",
            requestId,
            error: {
                code: ErrorCode.INVALID_REQUEST,
                message: `Project not found: ${sessionId}`,
            },
        });
        return;
    }
    try {
        // Query OpenCode for all sessions
        const response = await proxyToOpenCode({
            method: "GET",
            path: "/session",
        });
        if (response.status !== 200) {
            throw new Error(`OpenCode returned status ${response.status}`);
        }
        // Parse the response body
        let allSessions = [];
        if (response.body) {
            const parsed = JSON.parse(response.body);
            if (Array.isArray(parsed)) {
                allSessions = parsed;
            }
        }
        // Filter to only sessions for this project's path
        const projectPaths = new Set([project.path]);
        const filteredSessions = filterAndSortSessions(allSessions, projectPaths);
        send({
            type: "agent_sessions_list_response",
            requestId,
            payload: {
                sessions: filteredSessions.map((s) => ({
                    agentSessionId: s.id,
                    lastUsedAt: new Date(s.time.updated || s.time.created).toISOString(),
                    title: s.title || null,
                })),
            },
        });
    }
    catch (err) {
        const errorMessage = err instanceof Error ? err.message : String(err);
        logger.error(`agent_sessions_list error: ${errorMessage}`);
        const code = errorMessage === "OPENCODE_UNREACHABLE"
            ? ErrorCode.OPENCODE_UNREACHABLE
            : errorMessage === "TIMEOUT"
                ? ErrorCode.TIMEOUT
                : ErrorCode.UNKNOWN_ERROR;
        send({
            type: "agent_sessions_list_response",
            requestId,
            error: {
                code,
                message: errorMessage,
            },
        });
    }
}
//# sourceMappingURL=agent-sessions-list.js.map