// Coordinates the runtime-side TRPC handlers used by the browser.
// This is the main backend entrypoint for sessions, settings, git, and
// workspace actions, but detailed Cline, terminal, and config behavior
// should stay in focused services instead of accumulating here.

!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]="a399bc30-c916-5e5a-ba11-d58d85ca5ce2")}catch(e){}}();
import { rm } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import { TRPCError } from "@trpc/server";
import { createClineMcpRuntimeService } from "../cline-sdk/cline-mcp-runtime-service.js";
import { createClineMcpSettingsService } from "../cline-sdk/cline-mcp-settings-service.js";
import { createClineProviderService } from "../cline-sdk/cline-provider-service.js";
import { createClineSdkUserInstructionWatcher, listClineSdkWorkflowSlashCommands, } from "../cline-sdk/sdk-runtime-boundary.js";
import { updateGlobalRuntimeConfig, updateRuntimeConfig } from "../config/runtime-config.js";
import { parseClineMcpOAuthRequest, parseClineMcpSettingsSaveRequest, parseClineOauthLoginRequest, parseClineProviderModelsRequest, parseClineProviderSettingsSaveRequest, parseCommandRunRequest, parseRuntimeConfigSaveRequest, parseShellSessionStartRequest, parseTaskChatAbortRequest, parseTaskChatReloadRequest, parseTaskChatCancelRequest, parseTaskChatMessagesRequest, parseTaskChatSendRequest, parseTaskSessionInputRequest, parseTaskSessionStartRequest, parseTaskSessionStopRequest, } from "../core/api-validation.js";
import { isHomeAgentSessionId } from "../core/home-agent-session.js";
import { openInBrowser } from "../server/browser.js";
import { buildRuntimeConfigResponse, resolveAgentCommand } from "../terminal/agent-registry.js";
import { resolveTaskCwd } from "../workspace/task-worktree.js";
import { captureTaskTurnCheckpoint } from "../workspace/turn-checkpoints.js";
async function resolveExistingTaskCwdOrEnsure(options) {
    try {
        return await resolveTaskCwd({
            cwd: options.cwd,
            taskId: options.taskId,
            baseRef: options.baseRef,
            ensure: false,
        });
    }
    catch {
        return await resolveTaskCwd({
            cwd: options.cwd,
            taskId: options.taskId,
            baseRef: options.baseRef,
            ensure: true,
        });
    }
}
export function createRuntimeApi(deps) {
    const clineProviderService = createClineProviderService();
    const clineMcpSettingsService = createClineMcpSettingsService();
    const clineMcpRuntimeService = createClineMcpRuntimeService({
        onAuthStatusesChanged: (statuses) => {
            deps.broadcastClineMcpAuthStatusesUpdated?.(statuses);
        },
    });
    const debugResetTargetPaths = [
        join(homedir(), ".cline", "data"),
        join(homedir(), ".cline", "kanban"),
        join(homedir(), ".cline", "worktrees"),
    ];
    const buildConfigResponse = (runtimeConfig) => buildRuntimeConfigResponse(runtimeConfig, clineProviderService.getProviderSettingsSummary());
    return {
        loadConfig: async (workspaceScope) => {
            const activeRuntimeConfig = deps.getActiveRuntimeConfig?.();
            if (!workspaceScope && !activeRuntimeConfig) {
                throw new Error("No active runtime config provider is available.");
            }
            let scopedRuntimeConfig;
            if (workspaceScope) {
                scopedRuntimeConfig = await deps.loadScopedRuntimeConfig(workspaceScope);
            }
            else if (activeRuntimeConfig) {
                scopedRuntimeConfig = activeRuntimeConfig;
            }
            else {
                throw new Error("No active runtime config provider is available.");
            }
            return buildConfigResponse(scopedRuntimeConfig);
        },
        saveConfig: async (workspaceScope, input) => {
            const parsed = parseRuntimeConfigSaveRequest(input);
            let nextRuntimeConfig;
            if (workspaceScope) {
                nextRuntimeConfig = await updateRuntimeConfig(workspaceScope.workspacePath, parsed);
            }
            else {
                const activeRuntimeConfig = deps.getActiveRuntimeConfig?.();
                if (!activeRuntimeConfig) {
                    throw new TRPCError({
                        code: "BAD_REQUEST",
                        message: "No active runtime config is available.",
                    });
                }
                nextRuntimeConfig = await updateGlobalRuntimeConfig(activeRuntimeConfig, parsed);
            }
            if (workspaceScope && workspaceScope.workspaceId === deps.getActiveWorkspaceId()) {
                deps.setActiveRuntimeConfig(nextRuntimeConfig);
            }
            if (!workspaceScope) {
                deps.setActiveRuntimeConfig(nextRuntimeConfig);
            }
            return buildConfigResponse(nextRuntimeConfig);
        },
        saveClineProviderSettings: async (_workspaceScope, input) => {
            const body = parseClineProviderSettingsSaveRequest(input);
            return clineProviderService.saveProviderSettings(body);
        },
        startTaskSession: async (workspaceScope, input) => {
            try {
                const body = parseTaskSessionStartRequest(input);
                const requestedTaskMode = body.mode ?? (body.startInPlanMode ? "plan" : "act");
                const scopedRuntimeConfig = await deps.loadScopedRuntimeConfig(workspaceScope);
                const taskCwd = isHomeAgentSessionId(body.taskId)
                    ? workspaceScope.workspacePath
                    : await resolveExistingTaskCwdOrEnsure({
                        cwd: workspaceScope.workspacePath,
                        taskId: body.taskId,
                        baseRef: body.baseRef,
                    });
                const shouldCaptureTurnCheckpoint = !body.resumeFromTrash && !isHomeAgentSessionId(body.taskId);
                if (scopedRuntimeConfig.selectedAgentId === "cline") {
                    const clineLaunchConfig = await clineProviderService.resolveLaunchConfig();
                    const clineTaskSessionService = await deps.getScopedClineTaskSessionService(workspaceScope);
                    const summary = await clineTaskSessionService.startTaskSession({
                        taskId: body.taskId,
                        cwd: taskCwd,
                        prompt: body.prompt,
                        images: body.images,
                        resumeFromTrash: body.resumeFromTrash,
                        providerId: clineLaunchConfig.providerId,
                        modelId: clineLaunchConfig.modelId,
                        mode: requestedTaskMode,
                        apiKey: clineLaunchConfig.apiKey,
                        baseUrl: clineLaunchConfig.baseUrl,
                        reasoningEffort: clineLaunchConfig.reasoningEffort,
                    });
                    let nextSummary = summary;
                    if (shouldCaptureTurnCheckpoint) {
                        try {
                            const nextTurn = (summary.latestTurnCheckpoint?.turn ?? 0) + 1;
                            const checkpoint = await captureTaskTurnCheckpoint({
                                cwd: taskCwd,
                                taskId: body.taskId,
                                turn: nextTurn,
                            });
                            nextSummary = clineTaskSessionService.applyTurnCheckpoint(body.taskId, checkpoint) ?? summary;
                        }
                        catch {
                            // Best effort checkpointing only.
                        }
                    }
                    return {
                        ok: true,
                        summary: nextSummary,
                    };
                }
                const resolved = resolveAgentCommand(scopedRuntimeConfig);
                if (!resolved) {
                    return {
                        ok: false,
                        summary: null,
                        error: "No runnable agent command is configured. Open Settings, install a supported CLI, and select it.",
                    };
                }
                const terminalManager = await deps.getScopedTerminalManager(workspaceScope);
                const summary = await terminalManager.startTaskSession({
                    taskId: body.taskId,
                    agentId: resolved.agentId,
                    binary: resolved.binary,
                    args: resolved.args,
                    autonomousModeEnabled: scopedRuntimeConfig.agentAutonomousModeEnabled,
                    cwd: taskCwd,
                    prompt: body.prompt,
                    images: body.images,
                    startInPlanMode: body.startInPlanMode,
                    resumeFromTrash: body.resumeFromTrash,
                    cols: body.cols,
                    rows: body.rows,
                    workspaceId: workspaceScope.workspaceId,
                });
                let nextSummary = summary;
                if (shouldCaptureTurnCheckpoint) {
                    try {
                        const nextTurn = (summary.latestTurnCheckpoint?.turn ?? 0) + 1;
                        const checkpoint = await captureTaskTurnCheckpoint({
                            cwd: taskCwd,
                            taskId: body.taskId,
                            turn: nextTurn,
                        });
                        nextSummary = terminalManager.applyTurnCheckpoint(body.taskId, checkpoint) ?? summary;
                    }
                    catch {
                        // Best effort checkpointing only.
                    }
                }
                return {
                    ok: true,
                    summary: nextSummary,
                };
            }
            catch (error) {
                const message = error instanceof Error ? error.message : String(error);
                return {
                    ok: false,
                    summary: null,
                    error: message,
                };
            }
        },
        stopTaskSession: async (workspaceScope, input) => {
            try {
                const body = parseTaskSessionStopRequest(input);
                const clineTaskSessionService = await deps.getScopedClineTaskSessionService(workspaceScope);
                const clineSummary = await clineTaskSessionService.stopTaskSession(body.taskId);
                if (clineSummary) {
                    return {
                        ok: true,
                        summary: clineSummary,
                    };
                }
                const terminalManager = await deps.getScopedTerminalManager(workspaceScope);
                const summary = terminalManager.stopTaskSession(body.taskId);
                return {
                    ok: Boolean(summary),
                    summary,
                };
            }
            catch (error) {
                const message = error instanceof Error ? error.message : String(error);
                return {
                    ok: false,
                    summary: null,
                    error: message,
                };
            }
        },
        sendTaskSessionInput: async (workspaceScope, input) => {
            try {
                const body = parseTaskSessionInputRequest(input);
                const payloadText = body.appendNewline ? `${body.text}\n` : body.text;
                const clineTaskSessionService = await deps.getScopedClineTaskSessionService(workspaceScope);
                const clineSummary = await clineTaskSessionService.sendTaskSessionInput(body.taskId, payloadText);
                if (clineSummary) {
                    return {
                        ok: true,
                        summary: clineSummary,
                    };
                }
                const terminalManager = await deps.getScopedTerminalManager(workspaceScope);
                const summary = terminalManager.writeInput(body.taskId, Buffer.from(payloadText, "utf8"));
                if (!summary) {
                    return {
                        ok: false,
                        summary: null,
                        error: "Task session is not running.",
                    };
                }
                return {
                    ok: true,
                    summary,
                };
            }
            catch (error) {
                const message = error instanceof Error ? error.message : String(error);
                return {
                    ok: false,
                    summary: null,
                    error: message,
                };
            }
        },
        getTaskChatMessages: async (workspaceScope, input) => {
            try {
                const body = parseTaskChatMessagesRequest(input);
                const clineTaskSessionService = await deps.getScopedClineTaskSessionService(workspaceScope);
                const summary = clineTaskSessionService.getSummary(body.taskId);
                const messages = await clineTaskSessionService.loadTaskSessionMessages(body.taskId);
                if (!summary && messages.length === 0) {
                    return {
                        ok: false,
                        messages: [],
                        error: "Task chat session is not available.",
                    };
                }
                return {
                    ok: true,
                    messages,
                };
            }
            catch (error) {
                const message = error instanceof Error ? error.message : String(error);
                return {
                    ok: false,
                    messages: [],
                    error: message,
                };
            }
        },
        getClineSlashCommands: async (workspaceScope) => {
            const watcher = workspaceScope
                ? createClineSdkUserInstructionWatcher(workspaceScope.workspacePath)
                : undefined;
            if (watcher) {
                await watcher.refreshAll();
            }
            return {
                commands: listClineSdkWorkflowSlashCommands(watcher),
            };
        },
        reloadTaskChatSession: async (workspaceScope, input) => {
            try {
                const body = parseTaskChatReloadRequest(input);
                const clineTaskSessionService = await deps.getScopedClineTaskSessionService(workspaceScope);
                const summary = await clineTaskSessionService.reloadTaskSession(body.taskId);
                if (!summary) {
                    return {
                        ok: false,
                        summary: null,
                        error: "Task chat session is not available.",
                    };
                }
                return {
                    ok: true,
                    summary,
                };
            }
            catch (error) {
                const message = error instanceof Error ? error.message : String(error);
                return {
                    ok: false,
                    summary: null,
                    error: message,
                };
            }
        },
        abortTaskChatTurn: async (workspaceScope, input) => {
            try {
                const body = parseTaskChatAbortRequest(input);
                const clineTaskSessionService = await deps.getScopedClineTaskSessionService(workspaceScope);
                const summary = await clineTaskSessionService.abortTaskSession(body.taskId);
                if (!summary) {
                    return {
                        ok: false,
                        summary: null,
                        error: "Task chat session is not running.",
                    };
                }
                return {
                    ok: true,
                    summary,
                };
            }
            catch (error) {
                const message = error instanceof Error ? error.message : String(error);
                return {
                    ok: false,
                    summary: null,
                    error: message,
                };
            }
        },
        cancelTaskChatTurn: async (workspaceScope, input) => {
            try {
                const body = parseTaskChatCancelRequest(input);
                const clineTaskSessionService = await deps.getScopedClineTaskSessionService(workspaceScope);
                const summary = await clineTaskSessionService.cancelTaskTurn(body.taskId);
                if (!summary) {
                    return {
                        ok: false,
                        summary: null,
                        error: "Task chat session turn is not running.",
                    };
                }
                return {
                    ok: true,
                    summary,
                };
            }
            catch (error) {
                const message = error instanceof Error ? error.message : String(error);
                return {
                    ok: false,
                    summary: null,
                    error: message,
                };
            }
        },
        getClineProviderCatalog: async (_workspaceScope) => {
            return await clineProviderService.getProviderCatalog();
        },
        getClineAccountProfile: async (_workspaceScope) => {
            return await clineProviderService.getClineAccountProfile();
        },
        getClineKanbanAccess: async (_workspaceScope) => {
            return await clineProviderService.getClineKanbanAccess();
        },
        getClineProviderModels: async (_workspaceScope, input) => {
            const body = parseClineProviderModelsRequest(input);
            return await clineProviderService.getProviderModels(body.providerId);
        },
        getClineMcpAuthStatuses: async (_workspaceScope) => {
            const statuses = await clineMcpRuntimeService.getAuthStatuses();
            return {
                statuses,
            };
        },
        runClineMcpServerOAuth: async (_workspaceScope, input) => {
            const body = parseClineMcpOAuthRequest(input);
            const response = await clineMcpRuntimeService.authorizeServer({
                serverName: body.serverName,
                onAuthorizationUrl: (url) => {
                    openInBrowser(url);
                },
            });
            deps.bumpClineSessionContextVersion?.();
            return response;
        },
        getClineMcpSettings: async (_workspaceScope) => {
            return clineMcpSettingsService.loadSettings();
        },
        saveClineMcpSettings: async (_workspaceScope, input) => {
            const body = parseClineMcpSettingsSaveRequest(input);
            const response = await clineMcpSettingsService.saveSettings(body);
            deps.bumpClineSessionContextVersion?.();
            return response;
        },
        runClineProviderOAuthLogin: async (_workspaceScope, input) => {
            const body = parseClineOauthLoginRequest(input);
            return await clineProviderService.runOauthLogin({
                providerId: body.provider,
                baseUrl: body.baseUrl,
            });
        },
        sendTaskChatMessage: async (workspaceScope, input) => {
            try {
                const body = parseTaskChatSendRequest(input);
                const requestedMode = body.mode;
                const clineTaskSessionService = await deps.getScopedClineTaskSessionService(workspaceScope);
                let summary = await clineTaskSessionService.sendTaskSessionInput(body.taskId, body.text, requestedMode, body.images);
                if (!summary) {
                    if (!isHomeAgentSessionId(body.taskId)) {
                        const reboundSummary = await clineTaskSessionService.rebindPersistedTaskSession(body.taskId);
                        if (reboundSummary) {
                            summary = await clineTaskSessionService.sendTaskSessionInput(body.taskId, body.text, requestedMode, body.images);
                        }
                        if (!summary) {
                            return {
                                ok: false,
                                summary: null,
                                error: "Task chat session is not running.",
                            };
                        }
                    }
                    else {
                        const clineLaunchConfig = await clineProviderService.resolveLaunchConfig();
                        summary = await clineTaskSessionService.startTaskSession({
                            taskId: body.taskId,
                            cwd: workspaceScope.workspacePath,
                            prompt: body.text,
                            images: body.images,
                            providerId: clineLaunchConfig.providerId,
                            modelId: clineLaunchConfig.modelId,
                            mode: requestedMode,
                            apiKey: clineLaunchConfig.apiKey,
                            baseUrl: clineLaunchConfig.baseUrl,
                            reasoningEffort: clineLaunchConfig.reasoningEffort,
                        });
                    }
                }
                const latestMessage = clineTaskSessionService.listMessages(body.taskId).at(-1) ?? null;
                return {
                    ok: true,
                    summary,
                    message: latestMessage,
                };
            }
            catch (error) {
                const message = error instanceof Error ? error.message : String(error);
                return {
                    ok: false,
                    summary: null,
                    error: message,
                };
            }
        },
        startShellSession: async (workspaceScope, input) => {
            try {
                const body = parseShellSessionStartRequest(input);
                const terminalManager = await deps.getScopedTerminalManager(workspaceScope);
                const shell = deps.resolveInteractiveShellCommand();
                const shellCwd = body.workspaceTaskId
                    ? await resolveTaskCwd({
                        cwd: workspaceScope.workspacePath,
                        taskId: body.workspaceTaskId,
                        baseRef: body.baseRef,
                        ensure: true,
                    })
                    : workspaceScope.workspacePath;
                const summary = await terminalManager.startShellSession({
                    taskId: body.taskId,
                    cwd: shellCwd,
                    cols: body.cols,
                    rows: body.rows,
                    binary: shell.binary,
                    args: shell.args,
                });
                return {
                    ok: true,
                    summary,
                    shellBinary: shell.binary,
                };
            }
            catch (error) {
                const message = error instanceof Error ? error.message : String(error);
                return {
                    ok: false,
                    summary: null,
                    shellBinary: null,
                    error: message,
                };
            }
        },
        runCommand: async (workspaceScope, input) => {
            try {
                const body = parseCommandRunRequest(input);
                return await deps.runCommand(body.command, workspaceScope.workspacePath);
            }
            catch (error) {
                const message = error instanceof Error ? error.message : String(error);
                throw new TRPCError({
                    code: "INTERNAL_SERVER_ERROR",
                    message,
                });
            }
        },
        resetAllState: async (_workspaceScope) => {
            await deps.prepareForStateReset?.();
            await Promise.all(debugResetTargetPaths.map(async (path) => {
                await rm(path, { recursive: true, force: true });
            }));
            return {
                ok: true,
                clearedPaths: [...debugResetTargetPaths],
            };
        },
        openFile: async (input) => {
            const filePath = input.filePath.trim();
            if (!filePath) {
                throw new TRPCError({
                    code: "BAD_REQUEST",
                    message: "File path cannot be empty.",
                });
            }
            openInBrowser(filePath);
            return { ok: true };
        },
    };
}
//# sourceMappingURL=runtime-api.js.map
//# debugId=a399bc30-c916-5e5a-ba11-d58d85ca5ce2
