export class RuntimePersistence {
    turnStartTime = 0;
    toolStartTimes = new Map();
    callbacks = {};
    setCallbacks(callbacks) {
        this.callbacks = callbacks;
    }
    startInvocation(sessionStore, systemPrompt, tools) {
        this.turnStartTime = 0;
        this.toolStartTimes.clear();
        sessionStore.appendSystemPrompt(systemPrompt);
        sessionStore.appendToolDefinitions(tools);
    }
    handle(event, sessionStore, turnIndex) {
        switch (event.type) {
            case 'turn_start':
                this.turnStartTime = Date.now();
                sessionStore.appendTurnStart(turnIndex);
                return;
            case 'tool_execution_start':
                this.toolStartTimes.set(event.toolCallId, Date.now());
                return;
            case 'message_end':
                this.persistMessage(event.message, sessionStore);
                return;
            case 'turn_end':
                sessionStore.appendTurnEnd(turnIndex, this.turnStartTime > 0 ? Date.now() - this.turnStartTime : 0);
                return;
            default:
                return;
        }
    }
    persistMessage(message, sessionStore) {
        let entryId;
        if (message.role === 'assistant') {
            const durationMs = this.turnStartTime > 0 ? Date.now() - this.turnStartTime : undefined;
            const requestedEntryId = 'id' in message && typeof message.id === 'string' ? message.id : undefined;
            entryId = sessionStore.appendMessage(message, durationMs, requestedEntryId);
            // Host snapshots use session-entry ids as the stable UI message ids.
            // Stamp the same id onto the assistant object before run-stats reads it
            // so `last_message_id` anchors Copy/Usage/Share to the rendered message.
            message.id = entryId;
        }
        else if (message.role === 'toolResult') {
            const startTime = this.toolStartTimes.get(message.toolCallId);
            if (startTime !== undefined)
                this.toolStartTimes.delete(message.toolCallId);
            entryId = sessionStore.appendMessage(message, startTime === undefined ? undefined : Date.now() - startTime);
        }
        else if (message.role === 'user') {
            const requestedEntryId = 'id' in message && typeof message.id === 'string' ? message.id : undefined;
            entryId = sessionStore.appendMessage(message, undefined, requestedEntryId);
            message.id = entryId;
        }
        if (entryId !== undefined)
            this.callbacks.onMessagePersisted?.(entryId);
    }
}
//# sourceMappingURL=persistence.js.map