"use strict";
/**
 * Cache token tracking plugin (cache_read and cache_creation).
 *
 * Respects the dedup flag from TurnCounterPlugin.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheTrackerPlugin = void 0;
class CacheTrackerPlugin {
    name = 'cache';
    phaseRead = 0;
    phaseCreation = 0;
    phaseCreation5m = 0;
    phaseCreation1h = 0;
    totalRead = 0;
    totalCreation = 0;
    totalCreation5m = 0;
    totalCreation1h = 0;
    phaseSnapshots = [];
    currentPhase = 'setup';
    onMessage(message, ctx, store) {
        if (message.type !== 'assistant')
            return;
        const turns = ctx.get('turns');
        if (turns?.isDuplicate)
            return;
        const usage = message.message?.usage;
        if (usage) {
            const read = Number(usage.cache_read_input_tokens ?? 0);
            const creation = Number(usage.cache_creation_input_tokens ?? 0);
            const cc = usage.cache_creation;
            const creation5m = Number(cc?.ephemeral_5m_input_tokens ?? 0);
            const creation1h = Number(cc?.ephemeral_1h_input_tokens ?? 0);
            this.phaseRead += read;
            this.phaseCreation += creation;
            this.phaseCreation5m += creation5m;
            this.phaseCreation1h += creation1h;
            this.totalRead += read;
            this.totalCreation += creation;
        }
        store.set('cache', this.getData());
    }
    onPhaseTransition(fromPhase, toPhase, _ctx, store) {
        this.phaseSnapshots.push({
            phase: fromPhase,
            cacheReadTokens: this.phaseRead,
            cacheCreationTokens: this.phaseCreation,
            cacheCreation5m: this.phaseCreation5m,
            cacheCreation1h: this.phaseCreation1h,
        });
        this.currentPhase = toPhase;
        this.phaseRead = 0;
        this.phaseCreation = 0;
        this.phaseCreation5m = 0;
        this.phaseCreation1h = 0;
        store.set('cache', this.getData());
    }
    onFinalize(_resultMessage, _totalDurationMs, _ctx, store) {
        this.phaseSnapshots.push({
            phase: this.currentPhase,
            cacheReadTokens: this.phaseRead,
            cacheCreationTokens: this.phaseCreation,
            cacheCreation5m: this.phaseCreation5m,
            cacheCreation1h: this.phaseCreation1h,
        });
        store.set('cache', this.getData());
    }
    getData() {
        return {
            phaseRead: this.phaseRead,
            phaseCreation: this.phaseCreation,
            totalRead: this.totalRead,
            totalCreation: this.totalCreation,
            totalCreation5m: this.totalCreation5m,
            totalCreation1h: this.totalCreation1h,
            phaseSnapshots: [...this.phaseSnapshots],
        };
    }
}
exports.CacheTrackerPlugin = CacheTrackerPlugin;
