/**
 * Handler for agent_cancel messages.
 *
 * Aborts the running OpenCode session via POST /session/:id/abort.
 * The done event (with cancelled flag) comes via SSE.
 *
 * Per PRD: "Only cancel current run. The queue remains intact."
 */
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 handleAgentCancel(message, send) {
    const msg = message;
    const { requestId, sessionId } = msg;
    const { agentSessionId } = msg.payload;
    const project = getProject(sessionId);
    if (!project) {
        send({
            type: "error",
            requestId,
            error: {
                code: ErrorCode.INVALID_REQUEST,
                message: `Project not found: ${sessionId}`,
            },
        });
        return;
    }
    if (!agentSessionId || typeof agentSessionId !== "string") {
        send({
            type: "error",
            requestId,
            error: {
                code: ErrorCode.INVALID_REQUEST,
                message: "agentSessionId is required for agent_cancel",
            },
        });
        return;
    }
    try {
        const response = await proxyToOpenCode({
            method: "POST",
            path: `/session/${agentSessionId}/abort`,
        });
        if (response.status === 200 || response.status === 204) {
            logger.info(`Cancelled OpenCode session: ${agentSessionId}`);
        }
        else if (response.status === 404) {
            // Session not found - not an error, may have already finished
            logger.warn(`No running session to cancel: ${agentSessionId}`);
        }
        else {
            logger.warn(`Unexpected cancel response: ${response.status} for session ${agentSessionId}`);
        }
        // No response sent - the done event comes via SSE
    }
    catch (err) {
        const errorMessage = err instanceof Error ? err.message : String(err);
        // OPENCODE_UNREACHABLE is not fatal - just log it
        if (errorMessage === "OPENCODE_UNREACHABLE") {
            logger.warn(`Cannot cancel session ${agentSessionId}: OpenCode unreachable`);
            return;
        }
        logger.error(`agent_cancel error: ${errorMessage}`);
    }
}
//# sourceMappingURL=agent-cancel.js.map