/**
 * Middleware that monitors accumulated cost during a session (especially multi-turn tool calls)
 * and throws an error if a defined limit is exceeded.
 */
export class CostGuardMiddleware {
    options;
    name = "CostGuard";
    accumulatedCost = 0;
    constructor(options) {
        this.options = options;
        if (options.maxCost <= 0) {
            throw new Error("CostGuard maxCost must be greater than 0");
        }
    }
    async onResponse(ctx, result) {
        const cost = result.usage?.cost || 0;
        this.accumulatedCost += cost;
        if (this.accumulatedCost > this.options.maxCost) {
            this.options.onLimitExceeded?.(ctx, this.accumulatedCost);
            throw new Error(`[CostGuard] Budget exceeded. Accumulated cost $${this.accumulatedCost.toFixed(6)} exceeds limit $${this.options.maxCost.toFixed(6)}`);
        }
    }
}
/**
 * Factory function for creating the cost guard middleware.
 */
export function CostGuard(options) {
    return new CostGuardMiddleware(options);
}
