"use strict";
/**
 * Context size tracking plugin (context tokens in/out per phase).
 *
 * Context tokens out = sum of input + cache_read + cache_creation from the
 * last assistant message's usage (per-turn, NOT aggregate).
 * Context tokens in = previous phase's context tokens out.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextSizeTrackerPlugin = void 0;
class ContextSizeTrackerPlugin {
    name = 'contextSize';
    phaseSnapshots = [];
    lastContextTokensOut;
    onPhaseTransition(fromPhase, _toPhase, ctx, store) {
        const tokens = ctx.get('tokens');
        const contextTokensOut = this.computeContextTokensOut(tokens?.lastUsage);
        this.phaseSnapshots.push({
            phase: fromPhase,
            contextTokensIn: ctx.currentPhaseFreshContext
                ? undefined
                : this.lastContextTokensOut,
            contextTokensOut,
            freshContext: ctx.currentPhaseFreshContext,
        });
        this.lastContextTokensOut = contextTokensOut;
        store.set('contextSize', this.getData());
    }
    onFinalize(_resultMessage, _totalDurationMs, ctx, store) {
        const tokens = ctx.get('tokens');
        const contextTokensOut = this.computeContextTokensOut(tokens?.lastUsage);
        this.phaseSnapshots.push({
            phase: ctx.currentPhase,
            contextTokensIn: ctx.currentPhaseFreshContext
                ? undefined
                : this.lastContextTokensOut,
            contextTokensOut,
            freshContext: ctx.currentPhaseFreshContext,
        });
        store.set('contextSize', this.getData());
    }
    computeContextTokensOut(usage) {
        if (!usage)
            return undefined;
        return (Number(usage.input_tokens ?? 0) +
            Number(usage.cache_read_input_tokens ?? 0) +
            Number(usage.cache_creation_input_tokens ?? 0));
    }
    getData() {
        return {
            phaseSnapshots: [...this.phaseSnapshots],
        };
    }
}
exports.ContextSizeTrackerPlugin = ContextSizeTrackerPlugin;
