
!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]="8d604f9b-1a21-5808-af54-232d3a3857cb")}catch(e){}}();
import { cloneMessage, cloneSummary, createDefaultSummary, createMessage, createMessageWithMeta, finishToolCallMessage, startToolCallMessage, updateSummary, } from "./cline-session-state.js";
// Own the in-memory task entries plus summary and message fanout, so future SDK-backed hydration can slot in behind one boundary.
export class InMemoryClineMessageRepository {
    entries = new Map();
    hydratedMessagesByTaskId = new Map();
    summaryListeners = new Set();
    messageListeners = new Set();
    onSummary(listener) {
        this.summaryListeners.add(listener);
        return () => {
            this.summaryListeners.delete(listener);
        };
    }
    onMessage(listener) {
        this.messageListeners.add(listener);
        return () => {
            this.messageListeners.delete(listener);
        };
    }
    setTaskEntry(taskId, entry) {
        this.entries.set(taskId, entry);
        this.hydratedMessagesByTaskId.delete(taskId);
    }
    getTaskEntry(taskId) {
        return this.entries.get(taskId) ?? null;
    }
    getSummary(taskId) {
        const entry = this.entries.get(taskId);
        return entry ? cloneSummary(entry.summary) : null;
    }
    listSummaries() {
        return Array.from(this.entries.values()).map((entry) => cloneSummary(entry.summary));
    }
    listMessages(taskId) {
        const entry = this.entries.get(taskId);
        if (entry) {
            return entry.messages.map((message) => cloneMessage(message));
        }
        const hydratedMessages = this.hydratedMessagesByTaskId.get(taskId);
        return hydratedMessages ? hydratedMessages.map((message) => cloneMessage(message)) : [];
    }
    async hydrateTaskMessages(taskId, loadPersistedSession) {
        const liveEntry = this.entries.get(taskId);
        if (liveEntry) {
            return liveEntry.messages.map((message) => cloneMessage(message));
        }
        const cachedMessages = this.hydratedMessagesByTaskId.get(taskId);
        if (cachedMessages) {
            return cachedMessages.map((message) => cloneMessage(message));
        }
        const persistedSession = await loadPersistedSession();
        if (!persistedSession) {
            return [];
        }
        const hydratedMessages = hydratePersistedSessionMessages(taskId, persistedSession.messages);
        this.hydratedMessagesByTaskId.set(taskId, hydratedMessages);
        return hydratedMessages.map((message) => cloneMessage(message));
    }
    emitSummary(summary) {
        const snapshot = cloneSummary(summary);
        for (const listener of this.summaryListeners) {
            listener(snapshot);
        }
    }
    emitMessage(taskId, message) {
        const snapshot = cloneMessage(message);
        for (const listener of this.messageListeners) {
            listener(taskId, snapshot);
        }
    }
    applyTurnCheckpoint(taskId, checkpoint) {
        const entry = this.entries.get(taskId);
        if (!entry) {
            return null;
        }
        return updateSummary(entry, {
            latestTurnCheckpoint: checkpoint,
            previousTurnCheckpoint: entry.summary.latestTurnCheckpoint ?? null,
        });
    }
    dispose() {
        this.entries.clear();
        this.hydratedMessagesByTaskId.clear();
        this.summaryListeners.clear();
        this.messageListeners.clear();
    }
}
export function createInMemoryClineMessageRepository() {
    return new InMemoryClineMessageRepository();
}
export function createTaskEntryFromPersistedSession(taskId, messages, summaryPatch = {}) {
    const entry = createHydrationEntry(taskId);
    for (const message of messages) {
        hydratePersistedMessage(entry, taskId, message);
    }
    entry.summary = {
        ...entry.summary,
        ...summaryPatch,
        taskId,
        updatedAt: Date.now(),
    };
    return entry;
}
function hydratePersistedSessionMessages(taskId, messages) {
    const entry = createHydrationEntry(taskId);
    for (const message of messages) {
        hydratePersistedMessage(entry, taskId, message);
    }
    return entry.messages.map((message) => cloneMessage(message));
}
function createHydrationEntry(taskId) {
    return {
        summary: createDefaultSummary(taskId),
        messages: [],
        activeAssistantMessageId: null,
        activeReasoningMessageId: null,
        toolMessageIdByToolCallId: new Map(),
        toolInputByToolCallId: new Map(),
    };
}
function hydratePersistedMessage(entry, taskId, message) {
    const record = message && typeof message === "object" ? message : null;
    const persistedMetadata = record?.metadata && typeof record.metadata === "object" && !Array.isArray(record.metadata)
        ? record.metadata
        : null;
    const persistedDisplayRole = typeof persistedMetadata?.displayRole === "string" ? persistedMetadata.displayRole.trim().toLowerCase() : "";
    const persistedReason = typeof persistedMetadata?.reason === "string" ? persistedMetadata.reason.trim() : null;
    const persistedMessageKind = typeof persistedMetadata?.kind === "string" ? persistedMetadata.kind.trim() : null;
    const hydratedRole = persistedDisplayRole === "system" || persistedDisplayRole === "status"
        ? persistedDisplayRole
        : message.role;
    if (typeof message.content === "string") {
        appendPersistedTextMessage(entry, taskId, hydratedRole, message.content, persistedMetadata, persistedReason, persistedMessageKind);
        return;
    }
    const textParts = [];
    const images = [];
    const flushRichMessage = () => {
        if (textParts.length === 0 && images.length === 0) {
            return;
        }
        appendPersistedTextMessage(entry, taskId, hydratedRole, textParts.join("\n"), persistedMetadata, persistedReason, persistedMessageKind, images);
        textParts.length = 0;
        images.length = 0;
    };
    for (const block of message.content) {
        if (block.type === "text") {
            textParts.push(block.text);
            continue;
        }
        if (block.type === "file") {
            textParts.push(`Attached file: ${block.path}`);
            continue;
        }
        if (block.type === "image") {
            if (typeof block.data === "string" && typeof block.mediaType === "string") {
                images.push({
                    id: `${taskId}-image-${images.length}-${Date.now()}`,
                    data: block.data,
                    mimeType: block.mediaType,
                });
            }
            else if (typeof block.mediaType === "string") {
                textParts.push(`Attached image: ${block.mediaType}`);
            }
            continue;
        }
        flushRichMessage();
        if (block.type === "thinking") {
            appendPersistedReasoningMessage(entry, taskId, block.thinking);
            continue;
        }
        if (block.type === "redacted_thinking") {
            appendPersistedReasoningMessage(entry, taskId, "[redacted reasoning]");
            continue;
        }
        if (block.type === "tool_use") {
            startToolCallMessage(entry, taskId, {
                toolName: block.name,
                toolCallId: block.id,
                input: block.input,
            });
            continue;
        }
        if (block.type === "tool_result") {
            const resultText = stringifyPersistedToolResult(block.content);
            finishToolCallMessage(entry, taskId, {
                toolName: readHydratedToolName(entry, block.tool_use_id),
                toolCallId: block.tool_use_id,
                output: block.is_error ? undefined : resultText,
                error: block.is_error ? resultText : null,
                durationMs: null,
            });
        }
    }
    flushRichMessage();
}
function appendPersistedTextMessage(entry, taskId, role, content, metadata, reason, messageKind, images) {
    if (content.trim().length === 0 && (!images || images.length === 0)) {
        return;
    }
    const meta = metadata || reason || messageKind
        ? {
            hookEventName: metadata ? "history_notice" : null,
            messageKind: messageKind ?? null,
            displayRole: typeof metadata?.displayRole === "string" ? metadata.displayRole : null,
            reason: reason ?? null,
        }
        : null;
    entry.messages.push(meta ? createMessageWithMeta(taskId, role, content, meta, images) : createMessage(taskId, role, content, images));
}
function appendPersistedReasoningMessage(entry, taskId, content) {
    if (content.trim().length === 0) {
        return;
    }
    entry.messages.push(createMessageWithMeta(taskId, "reasoning", content, {
        streamType: "reasoning",
    }));
}
function stringifyPersistedToolResult(content) {
    if (typeof content === "string") {
        return content;
    }
    return content
        .map((block) => {
        if (block.type === "text" && typeof block.text === "string") {
            return block.text;
        }
        if (block.type === "file" && typeof block.path === "string") {
            return `Attached file: ${block.path}`;
        }
        if (block.type === "image" && typeof block.mediaType === "string") {
            return `Attached image: ${block.mediaType}`;
        }
        try {
            return JSON.stringify(block, null, 2);
        }
        catch {
            return String(block);
        }
    })
        .filter((part) => part.trim().length > 0)
        .join("\n");
}
function readHydratedToolName(entry, toolCallId) {
    const messageId = entry.toolMessageIdByToolCallId.get(toolCallId);
    if (!messageId) {
        return null;
    }
    const existingMessage = entry.messages.find((message) => message.id === messageId);
    return existingMessage?.meta?.toolName ?? null;
}
//# sourceMappingURL=cline-message-repository.js.map
//# debugId=8d604f9b-1a21-5808-af54-232d3a3857cb
