
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a2b265ff-4dd4-5e5b-afcf-8d0ac96719be")}catch(e){}}();
import { TRPCError } from "@trpc/server";
import { parseGitCheckoutRequest, parseWorktreeDeleteRequest, parseWorktreeEnsureRequest, } from "../core/api-validation.js";
import { saveWorkspaceState, WorkspaceStateConflictError } from "../state/workspace-state.js";
import { createEmptyWorkspaceChangesResponse, getWorkspaceChanges, getWorkspaceChangesBetweenRefs, getWorkspaceChangesFromRef, } from "../workspace/get-workspace-changes.js";
import { getCommitDiff, getGitLog, getGitRefs } from "../workspace/git-history.js";
import { discardGitChanges, getGitSyncSummary, runGitCheckoutAction, runGitSyncAction } from "../workspace/git-sync.js";
import { searchWorkspaceFiles } from "../workspace/search-workspace-files.js";
import { deleteTaskWorktree, ensureTaskWorktreeIfDoesntExist, getTaskWorkspaceInfo, resolveTaskCwd, } from "../workspace/task-worktree.js";
function normalizeOptionalTaskWorkspaceScopeInput(input) {
    if (!input) {
        return null;
    }
    const taskId = input.taskId.trim();
    const baseRef = input.baseRef.trim();
    if (!taskId || !baseRef) {
        throw new Error("baseRef query parameter requires taskId.");
    }
    return {
        taskId,
        baseRef,
    };
}
function normalizeRequiredTaskWorkspaceScopeInput(input) {
    const taskId = input.taskId.trim();
    const baseRef = input.baseRef.trim();
    if (!taskId) {
        throw new Error("Missing taskId query parameter.");
    }
    if (!baseRef) {
        throw new Error("Missing baseRef query parameter.");
    }
    const mode = input.mode ?? "working_copy";
    return {
        taskId,
        baseRef,
        mode,
    };
}
function isActiveTaskSessionState(summary) {
    return summary?.state === "running" || summary?.state === "awaiting_review";
}
function selectLastTurnSummary(terminalSummary, clineSummary) {
    if (!terminalSummary) {
        return clineSummary;
    }
    if (!clineSummary) {
        return terminalSummary;
    }
    const terminalIsActive = isActiveTaskSessionState(terminalSummary);
    const clineIsActive = isActiveTaskSessionState(clineSummary);
    if (terminalIsActive !== clineIsActive) {
        return clineIsActive ? clineSummary : terminalSummary;
    }
    if (terminalSummary.updatedAt !== clineSummary.updatedAt) {
        return terminalSummary.updatedAt > clineSummary.updatedAt ? terminalSummary : clineSummary;
    }
    if (clineSummary.agentId === "cline" && terminalSummary.agentId !== "cline") {
        return clineSummary;
    }
    return terminalSummary;
}
function createEmptyGitSummaryErrorResponse(error) {
    const message = error instanceof Error ? error.message : String(error);
    return {
        ok: false,
        summary: {
            currentBranch: null,
            upstreamBranch: null,
            changedFiles: 0,
            additions: 0,
            deletions: 0,
            aheadCount: 0,
            behindCount: 0,
        },
        error: message,
    };
}
function createEmptyGitSyncErrorResponse(action, error) {
    const message = error instanceof Error ? error.message : String(error);
    return {
        ok: false,
        action,
        summary: {
            currentBranch: null,
            upstreamBranch: null,
            changedFiles: 0,
            additions: 0,
            deletions: 0,
            aheadCount: 0,
            behindCount: 0,
        },
        output: "",
        error: message,
    };
}
function createEmptyGitCheckoutErrorResponse(error) {
    const message = error instanceof Error ? error.message : String(error);
    return {
        ok: false,
        branch: "",
        summary: {
            currentBranch: null,
            upstreamBranch: null,
            changedFiles: 0,
            additions: 0,
            deletions: 0,
            aheadCount: 0,
            behindCount: 0,
        },
        output: "",
        error: message,
    };
}
function createEmptyGitDiscardErrorResponse(error) {
    const message = error instanceof Error ? error.message : String(error);
    return {
        ok: false,
        summary: {
            currentBranch: null,
            upstreamBranch: null,
            changedFiles: 0,
            additions: 0,
            deletions: 0,
            aheadCount: 0,
            behindCount: 0,
        },
        output: "",
        error: message,
    };
}
export function createWorkspaceApi(deps) {
    return {
        loadGitSummary: async (workspaceScope, input) => {
            try {
                const taskScope = normalizeOptionalTaskWorkspaceScopeInput(input);
                let summaryCwd = workspaceScope.workspacePath;
                if (taskScope) {
                    summaryCwd = await resolveTaskCwd({
                        cwd: workspaceScope.workspacePath,
                        taskId: taskScope.taskId,
                        baseRef: taskScope.baseRef,
                        ensure: false,
                    });
                }
                const summary = await getGitSyncSummary(summaryCwd);
                return {
                    ok: true,
                    summary,
                };
            }
            catch (error) {
                return createEmptyGitSummaryErrorResponse(error);
            }
        },
        runGitSyncAction: async (workspaceScope, input) => {
            try {
                return await runGitSyncAction({
                    cwd: workspaceScope.workspacePath,
                    action: input.action,
                });
            }
            catch (error) {
                return createEmptyGitSyncErrorResponse(input.action, error);
            }
        },
        checkoutGitBranch: async (workspaceScope, input) => {
            try {
                const body = parseGitCheckoutRequest(input);
                const response = await runGitCheckoutAction({
                    cwd: workspaceScope.workspacePath,
                    branch: body.branch,
                });
                if (response.ok) {
                    void deps.broadcastRuntimeWorkspaceStateUpdated(workspaceScope.workspaceId, workspaceScope.workspacePath);
                }
                return response;
            }
            catch (error) {
                return createEmptyGitCheckoutErrorResponse(error);
            }
        },
        discardGitChanges: async (workspaceScope, input) => {
            try {
                const taskScope = normalizeOptionalTaskWorkspaceScopeInput(input);
                let discardCwd = workspaceScope.workspacePath;
                if (taskScope) {
                    discardCwd = await resolveTaskCwd({
                        cwd: workspaceScope.workspacePath,
                        taskId: taskScope.taskId,
                        baseRef: taskScope.baseRef,
                        ensure: false,
                    });
                }
                const response = await discardGitChanges({
                    cwd: discardCwd,
                });
                if (response.ok) {
                    void deps.broadcastRuntimeWorkspaceStateUpdated(workspaceScope.workspaceId, workspaceScope.workspacePath);
                }
                return response;
            }
            catch (error) {
                return createEmptyGitDiscardErrorResponse(error);
            }
        },
        loadChanges: async (workspaceScope, input) => {
            const normalizedInput = normalizeRequiredTaskWorkspaceScopeInput(input);
            const taskCwd = await resolveTaskCwd({
                cwd: workspaceScope.workspacePath,
                taskId: normalizedInput.taskId,
                baseRef: normalizedInput.baseRef,
                ensure: false,
            });
            if (normalizedInput.mode === "last_turn") {
                const terminalManager = await deps.ensureTerminalManagerForWorkspace(workspaceScope.workspaceId, workspaceScope.workspacePath);
                const clineTaskSessionService = await deps.getScopedClineTaskSessionService(workspaceScope);
                const summary = selectLastTurnSummary(terminalManager.getSummary(normalizedInput.taskId), clineTaskSessionService.getSummary(normalizedInput.taskId));
                const fromCheckpoint = summary?.previousTurnCheckpoint;
                const toCheckpoint = summary?.latestTurnCheckpoint;
                if (!toCheckpoint) {
                    return await createEmptyWorkspaceChangesResponse(taskCwd);
                }
                if (summary?.state === "running" || !fromCheckpoint) {
                    return await getWorkspaceChangesFromRef({
                        cwd: taskCwd,
                        fromRef: toCheckpoint.commit,
                    });
                }
                return await getWorkspaceChangesBetweenRefs({
                    cwd: taskCwd,
                    fromRef: fromCheckpoint.commit,
                    toRef: toCheckpoint.commit,
                });
            }
            return await getWorkspaceChanges(taskCwd);
        },
        ensureWorktree: async (workspaceScope, input) => {
            const body = parseWorktreeEnsureRequest(input);
            return await ensureTaskWorktreeIfDoesntExist({
                cwd: workspaceScope.workspacePath,
                taskId: body.taskId,
                baseRef: body.baseRef,
            });
        },
        deleteWorktree: async (workspaceScope, input) => {
            const body = parseWorktreeDeleteRequest(input);
            return await deleteTaskWorktree({
                repoPath: workspaceScope.workspacePath,
                taskId: body.taskId,
            });
        },
        loadTaskContext: async (workspaceScope, input) => {
            const normalizedInput = normalizeRequiredTaskWorkspaceScopeInput(input);
            return await getTaskWorkspaceInfo({
                cwd: workspaceScope.workspacePath,
                taskId: normalizedInput.taskId,
                baseRef: normalizedInput.baseRef,
            });
        },
        searchFiles: async (workspaceScope, input) => {
            const query = input.query.trim();
            const limit = input.limit;
            const files = await searchWorkspaceFiles(workspaceScope.workspacePath, query, limit);
            return {
                query,
                files,
            };
        },
        loadState: async (workspaceScope) => {
            return await deps.buildWorkspaceStateSnapshot(workspaceScope.workspaceId, workspaceScope.workspacePath);
        },
        notifyStateUpdated: async (workspaceScope) => {
            void deps.broadcastRuntimeWorkspaceStateUpdated(workspaceScope.workspaceId, workspaceScope.workspacePath);
            void deps.broadcastRuntimeProjectsUpdated(workspaceScope.workspaceId);
            return {
                ok: true,
            };
        },
        saveState: async (workspaceScope, input) => {
            try {
                const terminalManager = await deps.ensureTerminalManagerForWorkspace(workspaceScope.workspaceId, workspaceScope.workspacePath);
                for (const summary of terminalManager.listSummaries()) {
                    input.sessions[summary.taskId] = summary;
                }
                const response = await saveWorkspaceState(workspaceScope.workspacePath, input);
                void deps.broadcastRuntimeWorkspaceStateUpdated(workspaceScope.workspaceId, workspaceScope.workspacePath);
                void deps.broadcastRuntimeProjectsUpdated(workspaceScope.workspaceId);
                return response;
            }
            catch (error) {
                if (error instanceof WorkspaceStateConflictError) {
                    throw new TRPCError({
                        code: "CONFLICT",
                        message: error.message,
                        cause: {
                            currentRevision: error.currentRevision,
                        },
                    });
                }
                throw error;
            }
        },
        loadWorkspaceChanges: async (workspaceScope) => {
            return await getWorkspaceChanges(workspaceScope.workspacePath);
        },
        loadGitLog: async (workspaceScope, input) => {
            const taskScope = normalizeOptionalTaskWorkspaceScopeInput(input.taskScope ?? null);
            let logCwd = workspaceScope.workspacePath;
            if (taskScope) {
                logCwd = await resolveTaskCwd({
                    cwd: workspaceScope.workspacePath,
                    taskId: taskScope.taskId,
                    baseRef: taskScope.baseRef,
                    ensure: false,
                });
            }
            return await getGitLog({
                cwd: logCwd,
                ref: input.ref ?? null,
                refs: input.refs ?? null,
                maxCount: input.maxCount,
                skip: input.skip,
            });
        },
        loadGitRefs: async (workspaceScope, input) => {
            const taskScope = normalizeOptionalTaskWorkspaceScopeInput(input ?? null);
            let refsCwd = workspaceScope.workspacePath;
            if (taskScope) {
                refsCwd = await resolveTaskCwd({
                    cwd: workspaceScope.workspacePath,
                    taskId: taskScope.taskId,
                    baseRef: taskScope.baseRef,
                    ensure: false,
                });
            }
            return await getGitRefs(refsCwd);
        },
        loadCommitDiff: async (workspaceScope, input) => {
            const taskScope = normalizeOptionalTaskWorkspaceScopeInput(input.taskScope ?? null);
            let diffCwd = workspaceScope.workspacePath;
            if (taskScope) {
                diffCwd = await resolveTaskCwd({
                    cwd: workspaceScope.workspacePath,
                    taskId: taskScope.taskId,
                    baseRef: taskScope.baseRef,
                    ensure: false,
                });
            }
            return await getCommitDiff({
                cwd: diffCwd,
                commitHash: input.commitHash,
            });
        },
    };
}
//# sourceMappingURL=workspace-api.js.map
//# debugId=a2b265ff-4dd4-5e5b-afcf-8d0ac96719be
