/**
 * Handler for agent_session_new messages.
 * Creates a new OpenCode session and sends the first prompt.
 *
 * Uses OpenCode API:
 * - POST /session to create a new session
 * - POST /session/:id/prompt_async to send the first prompt
 *
 * Events are streamed via SSE subscription (not from this handler).
 */
import { ErrorCode } from "@pocketcoder/shared/constants";
import { getProject } from "../db/repositories/projects.js";
import { proxyToOpenCode } from "../opencode/proxy.js";
import { logger } from "../utils/logger.js";
export async function handleAgentSessionNew(message, send) {
    const msg = message;
    const { requestId, sessionId } = msg;
    const { content } = msg.payload;
    const project = getProject(sessionId);
    if (!project) {
        send({
            type: "agent_session_new_response",
            requestId,
            error: {
                code: ErrorCode.INVALID_REQUEST,
                message: `Project not found: ${sessionId}`,
            },
        });
        return;
    }
    if (!content || typeof content !== "string" || content.trim().length === 0) {
        send({
            type: "agent_session_new_response",
            requestId,
            error: {
                code: ErrorCode.INVALID_REQUEST,
                message: "content is required for agent_session_new",
            },
        });
        return;
    }
    try {
        // Step 1: Create a new session via OpenCode API
        const createResponse = await proxyToOpenCode({
            method: "POST",
            path: "/session",
            body: JSON.stringify({
                directory: project.path,
            }),
        });
        if (createResponse.status !== 200 && createResponse.status !== 201) {
            throw new Error(`OpenCode session create failed: ${createResponse.status}`);
        }
        const sessionData = JSON.parse(createResponse.body ?? "{}");
        const agentSessionId = sessionData.id;
        if (!agentSessionId) {
            throw new Error("OpenCode did not return a session ID");
        }
        // Send response immediately with the new session ID
        send({
            type: "agent_session_new_response",
            requestId,
            payload: {
                agentSessionId,
            },
        });
        // Step 2: Send the first prompt asynchronously
        // This kicks off the processing; events stream via SSE
        try {
            const promptResponse = await proxyToOpenCode({
                method: "POST",
                path: `/session/${agentSessionId}/prompt_async`,
                body: JSON.stringify({
                    content,
                }),
            });
            if (promptResponse.status !== 200 && promptResponse.status !== 202) {
                logger.warn(`agent_session_new prompt failed: ${promptResponse.status} - session ${agentSessionId}`);
            }
        }
        catch (promptErr) {
            const promptMessage = promptErr instanceof Error ? promptErr.message : String(promptErr);
            logger.error(`agent_session_new prompt error: ${promptMessage}`);
            // Don't send error response - the session was created successfully
            // and the client will see the session status via SSE
        }
    }
    catch (err) {
        const errorMessage = err instanceof Error ? err.message : String(err);
        logger.error(`agent_session_new error: ${errorMessage}`);
        const code = errorMessage === "OPENCODE_UNREACHABLE"
            ? ErrorCode.OPENCODE_UNREACHABLE
            : errorMessage === "TIMEOUT"
                ? ErrorCode.TIMEOUT
                : ErrorCode.UNKNOWN_ERROR;
        send({
            type: "agent_session_new_response",
            requestId,
            error: {
                code,
                message: errorMessage,
            },
        });
    }
}
//# sourceMappingURL=agent-session-new.js.map