import { T as TriggerSource } from './interfaces-elkYeYRS.js';
import { T as TriggerSourceName } from './types-GeEw7wzC.js';

type ModelId = string;
type QualityRequirement = "highest" | "high" | "balanced" | "efficient";
type TaskIntent = "document_analysis" | "drafting" | "classification" | "extraction" | "summarisation" | "code_generation" | "code_review" | "reasoning" | "conversation" | "other";
/** A single recorded API call with full attribution metadata. */
interface SpendRecord {
    id: string;
    modelId: ModelId;
    customerId: string;
    agentId: string;
    timestamp: Date;
    inputTokens: number;
    outputTokens: number;
    /** Cache write tokens (Anthropic prompt caching). */
    cacheWriteTokens: number;
    /** Cache read tokens — cheaper than input, 0.10× input price. */
    cacheReadTokens: number;
    /** Computed cost in USD. Filled by CostCalculator.computeRecordCost. */
    costUsd: number;
    /** Optional task intent tag for model-recommender analysis. */
    taskIntent?: TaskIntent;
}
/** Pricing for one model. All prices in USD per million tokens. */
interface ModelPricing {
    modelId: ModelId;
    displayName: string;
    provider: string;
    inputPerMillion: number;
    outputPerMillion: number;
    /** Cache write tokens — typically 1.25× input. 0 if caching not supported. */
    cacheWritePerMillion: number;
    /** Cache read tokens — typically 0.10× input. 0 if caching not supported. */
    cacheReadPerMillion: number;
    /** ISO-8601 date this pricing became effective (e.g. "2025-10-01"). */
    effectiveFrom: string;
}
/** Subscription tier definition for a customer category. */
interface CustomerTier {
    tierId: string;
    name: string;
    /** Monthly subscription revenue charged to the customer (USD). */
    monthlyRevenueUsd: number;
    /** Monthly AI spend cap — maximum acceptable spend for this tier (USD). */
    monthlySpendCapUsd: number;
    /** Target gross margin as a decimal: 0.7 = retain 70% of revenue. */
    targetMarginRatio: number;
}
/** Per-customer monthly margin snapshot. */
interface CustomerMargin {
    customerId: string;
    tierId: string;
    periodYear: number;
    periodMonth: number;
    totalSpendUsd: number;
    monthlyRevenueUsd: number;
    monthlySpendCapUsd: number;
    /** Target margin from the tier definition. */
    targetMarginRatio: number;
    /** Revenue minus spend in USD. Negative = over budget. */
    marginUsd: number;
    /** marginUsd / monthlyRevenueUsd. Negative = over budget. */
    marginRatio: number;
    /** totalSpendUsd / monthlySpendCapUsd. >1.0 = over cap. */
    capUtilisation: number;
    computedAt: Date;
}
type AnomalyType = "opus_spike" | "cache_hit_ratio_drop" | "customer_over_budget" | "customer_trending_over_budget" | "unusual_model_usage" | "spend_velocity_spike";
type AnomalySeverity = "warning" | "critical";
/** A detected anomaly in spend patterns. */
interface AnomalyDetectionResult {
    id: string;
    type: AnomalyType;
    severity: AnomalySeverity;
    customerId?: string;
    agentId?: string;
    modelId?: string;
    description: string;
    /** The observed metric value that triggered the alert. */
    observedValue: number;
    /** The configured threshold or baseline the value breached. */
    threshold: number;
    detectedAt: Date;
}
/** Margin alert produced by MarginMonitor on threshold breach. */
interface MarginAlert {
    customerId: string;
    tierId: string;
    alertType: "approaching_cap" | "over_cap" | "margin_below_target";
    /** Current cap utilisation fraction (0–1+). */
    capUtilisation: number;
    marginRatio: number;
    message: string;
    firedAt: Date;
}
/** Task description fed to ModelRecommender. */
interface TaskSignature {
    intent: TaskIntent;
    /** Estimated input token count, including system prompt and context. */
    estimatedInputTokens: number;
    /** Estimated output token count. */
    estimatedOutputTokens: number;
    qualityRequirement: QualityRequirement;
    /** True when system-prompt / context is stable enough to benefit from caching. */
    cacheableContext: boolean;
}
/**
 * A model swap recommendation produced by ModelRecommender.
 *
 * requiresApproval is always true — swaps NEVER apply automatically.
 * Consumers wire this into F0.6 Approval flow before changing model selection.
 */
interface ModelRecommendation {
    recommendedModelId: ModelId;
    currentModelId: ModelId;
    estimatedCostUsd: number;
    currentCostUsd: number;
    /** Estimated saving per month if swap is applied across call volume. */
    projectedMonthlySavingUsd: number;
    rationale: string;
    qualityPreserved: boolean;
    requiresApproval: true;
    generatedAt: Date;
}
/** Projected margin impact for one customer after a pricing change. */
interface PricingChangeImpact {
    customerId: string;
    tierId: string;
    previousProjectedSpendUsd: number;
    newProjectedSpendUsd: number;
    /** Positive = more expensive under new pricing. */
    deltaUsd: number;
    previousMarginRatio: number;
    newMarginRatio: number;
    atRisk: boolean;
    atRiskReason?: string;
    computedAt: Date;
}
/** Persistence for SpendRecord entries. Storage-agnostic. */
interface SpendStore {
    record(spend: SpendRecord): Promise<SpendRecord>;
    listByCustomer(customerId: string, opts?: {
        since?: Date;
        until?: Date;
    }): Promise<SpendRecord[]>;
    listByAgent(agentId: string, opts?: {
        since?: Date;
        until?: Date;
    }): Promise<SpendRecord[]>;
    /** Aggregated USD spend for a customer within a calendar month. */
    monthlySpendByCustomer(customerId: string, year: number, month: number): Promise<number>;
    listAll(opts?: {
        since?: Date;
        until?: Date;
    }): Promise<SpendRecord[]>;
}
/** Persistence for CustomerTier config and customer→tier assignments. */
interface CustomerTierStore {
    get(tierId: string): Promise<CustomerTier | null>;
    getByCustomer(customerId: string): Promise<CustomerTier | null>;
    upsert(tier: CustomerTier): Promise<CustomerTier>;
    assignTier(customerId: string, tierId: string): Promise<void>;
    listCustomers(tierId?: string): Promise<{
        customerId: string;
        tierId: string;
    }[]>;
}

/** Anthropic model pricing as of the last known update. USD per million tokens. */
declare const DEFAULT_PRICING: Record<string, ModelPricing>;
interface CostCalculatorConfig {
    /**
     * Merged on top of DEFAULT_PRICING. Use to add new models or update prices
     * without modifying source code. Partial entries are merged field-by-field.
     */
    pricingOverrides?: Record<string, Partial<ModelPricing>>;
}
declare class CostCalculator {
    private readonly pricing;
    constructor(config?: CostCalculatorConfig);
    getPricingTable(): Record<string, ModelPricing>;
    getPricing(modelId: ModelId): ModelPricing | null;
    /**
     * Computes USD cost for one API call.
     *
     * Returns 0 for unknown models — cost tracking must never block the call
     * path. Log unknown modelIds at the call site.
     */
    computeCost(modelId: ModelId, inputTokens: number, outputTokens: number, cacheWriteTokens?: number, cacheReadTokens?: number): number;
    /** Fills costUsd on a SpendRecord and returns the completed record. */
    computeRecordCost(record: Omit<SpendRecord, "costUsd">): SpendRecord;
    /**
     * Recomputes cost for an existing SpendRecord using the current pricing table.
     * Used by PricingChangeAdapter to project impact of price changes on historical spend.
     */
    recomputeCost(record: SpendRecord): number;
}

interface RecordParams {
    id: string;
    modelId: ModelId;
    customerId: string;
    agentId: string;
    inputTokens: number;
    outputTokens: number;
    cacheWriteTokens?: number;
    cacheReadTokens?: number;
    taskIntent?: TaskIntent;
    /** Defaults to now. */
    timestamp?: Date;
}
interface SpendTracker {
    record(params: RecordParams): Promise<SpendRecord>;
    getCustomerSpend(customerId: string, opts?: {
        since?: Date;
        until?: Date;
    }): Promise<SpendRecord[]>;
    getAgentSpend(agentId: string, opts?: {
        since?: Date;
        until?: Date;
    }): Promise<SpendRecord[]>;
    getMonthlySpend(customerId: string, year: number, month: number): Promise<number>;
    getAllSpend(opts?: {
        since?: Date;
        until?: Date;
    }): Promise<SpendRecord[]>;
}
declare class DefaultSpendTracker implements SpendTracker {
    private readonly store;
    private readonly calculator;
    constructor(store: SpendStore, calculator: CostCalculator);
    record(params: RecordParams): Promise<SpendRecord>;
    getCustomerSpend(customerId: string, opts?: {
        since?: Date;
        until?: Date;
    }): Promise<SpendRecord[]>;
    getAgentSpend(agentId: string, opts?: {
        since?: Date;
        until?: Date;
    }): Promise<SpendRecord[]>;
    getMonthlySpend(customerId: string, year: number, month: number): Promise<number>;
    getAllSpend(opts?: {
        since?: Date;
        until?: Date;
    }): Promise<SpendRecord[]>;
}

interface MarginMonitorConfig {
    /** Fire "approaching_cap" alert at this cap utilisation fraction. Default: 0.7. */
    approachingCapThreshold?: number;
    /** Fire "over_cap" alert at this cap utilisation fraction. Default: 1.0. */
    overCapThreshold?: number;
}
declare class MarginMonitor {
    private readonly spendStore;
    private readonly tierStore;
    private readonly approachingCap;
    private readonly overCap;
    constructor(spendStore: SpendStore, tierStore: CustomerTierStore, config?: MarginMonitorConfig);
    /**
     * Computes the current month's margin for one customer.
     *
     * Returns null if no tier is configured for the customer.
     */
    computeMargin(customerId: string, year: number, month: number, now?: Date): Promise<CustomerMargin | null>;
    /**
     * Checks all known customers for threshold breaches.
     * Intended for scheduled daily / weekly runs.
     */
    checkAll(year: number, month: number, now?: Date): Promise<MarginAlert[]>;
    /**
     * Evaluates threshold rules against a pre-computed margin snapshot.
     * Pure — no I/O. Safe to call from tests or pipeline logic.
     */
    evaluateAlerts(margin: CustomerMargin, now?: Date): MarginAlert[];
}

interface AnomalyThresholds {
    /**
     * Fraction of total spend on Opus-class models before firing "opus_spike".
     * Default: 0.3 (30%).
     */
    opusSpendFraction?: number;
    /**
     * Cache hit ratio below this level fires "cache_hit_ratio_drop".
     * Ratio = cacheReadTokens / (cacheReadTokens + cacheWriteTokens).
     * Default: 0.2 (20%).
     */
    cacheHitRatioMin?: number;
    /**
     * Minimum total cache tokens required before the hit-ratio check applies.
     * Prevents false alarms during cache warm-up. Default: 10_000.
     */
    cacheTokensWarmupMin?: number;
    /**
     * Multiplier on recent vs prior spend that fires "spend_velocity_spike".
     * Records are split chronologically into two halves for comparison.
     * Default: 3.0 (3× prior-period spend).
     */
    velocitySpikeMultiplier?: number;
}
/** Model IDs matching this pattern are considered "Opus-class". */
declare const OPUS_MODEL_PATTERN: RegExp;
declare class AnomalyDetector {
    private readonly spendStore;
    private readonly opusSpendFraction;
    private readonly cacheHitRatioMin;
    private readonly cacheTokensWarmupMin;
    private readonly velocitySpikeMultiplier;
    constructor(spendStore: SpendStore, thresholds?: AnomalyThresholds);
    /**
     * Runs all anomaly checks on a pre-fetched record set.
     * Pure — no I/O.
     */
    detectFromRecords(records: SpendRecord[], now?: Date): AnomalyDetectionResult[];
    /** Fetches a customer's monthly records and runs all checks. */
    detectForCustomer(customerId: string, year: number, month: number, now?: Date): Promise<AnomalyDetectionResult[]>;
    /** Fetches all records in the date range and runs all checks. */
    detectAll(opts: {
        since: Date;
        until: Date;
    }, now?: Date): Promise<AnomalyDetectionResult[]>;
    private checkOpusSpike;
    private checkCacheHitRatio;
    private checkSpendVelocitySpike;
}

/**
 * Maps each quality requirement to the model IDs that satisfy it, in
 * ascending cost preference order. The recommender picks the cheapest
 * viable model from the list.
 */
type QualityModelMap = Record<QualityRequirement, ModelId[]>;
declare const DEFAULT_QUALITY_MODEL_MAP: QualityModelMap;
interface ModelRecommenderConfig {
    qualityModelMap?: QualityModelMap;
    /**
     * Monthly call volume for this task signature.
     * Used to compute projectedMonthlySavingUsd. Default: 0.
     */
    monthlyCallVolume?: number;
}
declare class ModelRecommender {
    private readonly calculator;
    private readonly qualityModelMap;
    private readonly monthlyCallVolume;
    constructor(calculator: CostCalculator, config?: ModelRecommenderConfig);
    /**
     * Recommends the optimal model for the task signature.
     *
     * Returns null when the current model is already the cheapest viable
     * option, or when no pricing data exists for candidate models.
     */
    recommend(task: TaskSignature, currentModelId: ModelId, now?: Date): ModelRecommendation | null;
    private estimateCost;
    private buildRationale;
}

interface PricingChangeAdapterConfig {
    /**
     * How many historical months to use for projecting monthly spend.
     * Spend over the window is averaged to a per-month figure. Default: 1.
     */
    projectionMonths?: number;
}
declare class PricingChangeAdapter {
    private readonly spendStore;
    private readonly tierStore;
    /** CostCalculator with the pricing table before the change. */
    private readonly previousCalculator;
    /** CostCalculator with the updated pricing table. */
    private readonly newCalculator;
    private readonly projectionMonths;
    constructor(spendStore: SpendStore, tierStore: CustomerTierStore, 
    /** CostCalculator with the pricing table before the change. */
    previousCalculator: CostCalculator, 
    /** CostCalculator with the updated pricing table. */
    newCalculator: CostCalculator, config?: PricingChangeAdapterConfig);
    /**
     * Recomputes projected monthly spend for every known customer.
     *
     * Uses the prior `projectionMonths` of actual SpendRecords as the baseline,
     * applying both pricing tables to derive spend deltas. Results are sorted
     * by `deltaUsd` descending (most-impacted customers first).
     *
     * @param referenceDate  Month to project forward from (defaults to today).
     */
    recalculate(referenceDate?: Date, now?: Date): Promise<PricingChangeImpact[]>;
    /** Convenience — returns only at-risk customers from recalculate(). */
    atRiskCustomers(referenceDate?: Date, now?: Date): Promise<PricingChangeImpact[]>;
}

declare class InMemorySpendStore implements SpendStore {
    private readonly records;
    record(spend: SpendRecord): Promise<SpendRecord>;
    listByCustomer(customerId: string, opts?: {
        since?: Date;
        until?: Date;
    }): Promise<SpendRecord[]>;
    listByAgent(agentId: string, opts?: {
        since?: Date;
        until?: Date;
    }): Promise<SpendRecord[]>;
    monthlySpendByCustomer(customerId: string, year: number, month: number): Promise<number>;
    listAll(opts?: {
        since?: Date;
        until?: Date;
    }): Promise<SpendRecord[]>;
    /** Test helper — remove all records. */
    clear(): void;
    /** Test helper — current record count. */
    size(): number;
}
declare class InMemoryCustomerTierStore implements CustomerTierStore {
    private readonly tiers;
    private readonly assignments;
    get(tierId: string): Promise<CustomerTier | null>;
    getByCustomer(customerId: string): Promise<CustomerTier | null>;
    upsert(tier: CustomerTier): Promise<CustomerTier>;
    assignTier(customerId: string, tierId: string): Promise<void>;
    listCustomers(tierId?: string): Promise<{
        customerId: string;
        tierId: string;
    }[]>;
    /** Test helper — remove all tiers and assignments. */
    clear(): void;
}

interface SimpleLogger {
    info(message: string, meta?: Record<string, unknown>): void;
    warn(message: string, meta?: Record<string, unknown>): void;
}
interface ApiCallParams {
    id: string;
    modelId: string;
    customerId: string;
    agentId: string;
    inputTokens: number;
    outputTokens: number;
    cacheWriteTokens?: number;
    cacheReadTokens?: number;
    taskIntent?: TaskIntent;
    timestamp?: Date;
}
declare class ApiCallTracker {
    private readonly tracker;
    private readonly logger?;
    constructor(tracker: SpendTracker, logger?: SimpleLogger | undefined);
    /**
     * Records a single LLM API call as a SpendRecord via the injected tracker.
     * Emits a structured log line on success; warns on unknown models (costUsd === 0).
     */
    trackApiCall(params: ApiCallParams): Promise<SpendRecord>;
    /**
     * Runs `call`, records the spend attribution, and returns both the call
     * result and the resulting SpendRecord.
     *
     * The spend is recorded even if `params` has an unknown modelId (costUsd
     * will be 0 and a warning is logged). The call's promise rejection is NOT
     * caught here — let it propagate naturally.
     */
    static wrap<T>(call: () => Promise<T>, tracker: ApiCallTracker, params: ApiCallParams): Promise<{
        result: T;
        spend: SpendRecord;
    }>;
}

/** Per-agent cache stats inside a CacheHitReport. */
interface AgentCacheStats {
    readTokens: number;
    writeTokens: number;
    hitRatio: number;
}
/** Per-workflow (taskIntent) cache stats inside a CacheHitReport. */
interface WorkflowCacheStats {
    readTokens: number;
    writeTokens: number;
    hitRatio: number;
}
/**
 * Cache efficiency report for a set of SpendRecords.
 *
 * hitRatio = totalCacheReadTokens / (totalCacheReadTokens + totalCacheWriteTokens)
 * A ratio close to 1.0 means most context is served from cache (cheap).
 * A ratio near 0 means little re-use — consider stable system-prompt caching.
 */
interface CacheHitReport {
    totalCacheReadTokens: number;
    totalCacheWriteTokens: number;
    /** Combined cache token count (read + write). */
    totalCacheTokens: number;
    /** cacheReadTokens / (cacheReadTokens + cacheWriteTokens). 0 if no cache tokens. */
    hitRatio: number;
    perAgent: Record<string, AgentCacheStats>;
    /** Grouped by taskIntent value. Only present when any record has a taskIntent. */
    perWorkflow?: Record<string, WorkflowCacheStats>;
}
declare class CacheHitTracker {
    private readonly spendStore;
    constructor(spendStore: SpendStore);
    /**
     * Computes cache efficiency over a pre-fetched record set.
     * Pure — no I/O.
     */
    analyzeCacheHits(records: SpendRecord[]): CacheHitReport;
    /**
     * Fetches all records for a customer within a calendar month and returns
     * the cache hit report.
     */
    loadAndAnalyzeForCustomer(customerId: string, year: number, month: number): Promise<CacheHitReport>;
}

type OcrProvider = "tesseract" | "aws_textract" | "google_vision" | "claude_vision";
/** Default cost per page (USD) by provider. Override via OcrTrackerConfig. */
declare const DEFAULT_OCR_COST_PER_PAGE: Record<OcrProvider, number>;
/** A single OCR usage event. Mirrors the SpendRecord shape for attribution. */
interface OcrUsageRecord {
    id: string;
    customerId: string;
    agentId: string;
    provider: OcrProvider;
    pagesProcessed: number;
    costUsd: number;
    durationMs?: number;
    timestamp: Date;
}
/** Persistence interface for OcrUsageRecords. */
interface OcrUsageStore {
    record(usage: OcrUsageRecord): Promise<OcrUsageRecord>;
    listByCustomer(customerId: string, opts?: {
        since?: Date;
        until?: Date;
    }): Promise<OcrUsageRecord[]>;
    listAll(opts?: {
        since?: Date;
        until?: Date;
    }): Promise<OcrUsageRecord[]>;
}
declare class InMemoryOcrUsageStore implements OcrUsageStore {
    private readonly records;
    record(usage: OcrUsageRecord): Promise<OcrUsageRecord>;
    listByCustomer(customerId: string, opts?: {
        since?: Date;
        until?: Date;
    }): Promise<OcrUsageRecord[]>;
    listAll(opts?: {
        since?: Date;
        until?: Date;
    }): Promise<OcrUsageRecord[]>;
    clear(): void;
    size(): number;
}
interface OcrTrackerConfig {
    /** Override cost-per-page (USD) for any provider. Merged over defaults. */
    costPerPage?: Partial<Record<OcrProvider, number>>;
}
/** Per-provider cost summary returned by costDifferential(). */
interface ProviderCostSummary {
    provider: OcrProvider;
    totalPages: number;
    totalCostUsd: number;
    avgCostPerPage: number;
}
/** Result of OcrTracker.costDifferential(). */
interface OcrCostDifferentialReport {
    perProvider: ProviderCostSummary[];
    cheapestProvider: OcrProvider;
    /** How much could have been saved if all pages used the cheapest provider. */
    potentialSavingUsd: number;
}
interface TrackOcrParams {
    id: string;
    customerId: string;
    agentId: string;
    provider: OcrProvider;
    pagesProcessed: number;
    /** Override computed cost. Falls back to costPerPage × pagesProcessed. */
    costUsd?: number;
    durationMs?: number;
    timestamp?: Date;
}
declare class OcrTracker {
    private readonly store;
    private readonly costPerPage;
    constructor(store: OcrUsageStore, config?: OcrTrackerConfig);
    /** Records an OCR usage event. Computes cost automatically unless overridden. */
    trackOcrUsage(params: TrackOcrParams): Promise<OcrUsageRecord>;
    /**
     * Compares actual spend across providers vs the cheapest available provider.
     * Pure — no I/O.
     */
    costDifferential(records: OcrUsageRecord[]): OcrCostDifferentialReport;
}

/** Attribution record stored alongside a SpendRecord for Batch API calls. */
interface BatchAttribution {
    /** Matches the SpendRecord id. */
    spendRecordId: string;
    viaBatchApi: boolean;
    /** The cost before the 50% discount (realtime equivalent). */
    realtimeCostUsd: number;
    /** The discounted cost recorded in the SpendRecord. */
    batchCostUsd: number;
    recordedAt: Date;
}
/** Persistence interface for BatchAttribution records. */
interface BatchAttributionStore {
    record(attribution: BatchAttribution): Promise<BatchAttribution>;
    listBySpendRecordId(spendRecordId: string): Promise<BatchAttribution | null>;
    listAll(): Promise<BatchAttribution[]>;
}
declare class InMemoryBatchAttributionStore implements BatchAttributionStore {
    private readonly records;
    record(attribution: BatchAttribution): Promise<BatchAttribution>;
    listBySpendRecordId(spendRecordId: string): Promise<BatchAttribution | null>;
    listAll(): Promise<BatchAttribution[]>;
    clear(): void;
    size(): number;
}
interface TrackBatchParams {
    id: string;
    modelId: string;
    customerId: string;
    agentId: string;
    inputTokens: number;
    outputTokens: number;
    /** When true, 50% discount is applied to the computed cost. */
    viaBatchApi: boolean;
    cacheWriteTokens?: number;
    cacheReadTokens?: number;
    taskIntent?: TaskIntent;
    timestamp?: Date;
}
/** Summary comparing batch spend vs what realtime would have cost. */
interface BatchSavingsReport {
    totalBatchSpendUsd: number;
    equivalentRealtimeSpendUsd: number;
    savingsUsd: number;
    savingsPercent: number;
}
declare class BatchTracker {
    private readonly tracker;
    private readonly calculator;
    private readonly attributionStore;
    constructor(tracker: SpendTracker, calculator: CostCalculator, attributionStore: BatchAttributionStore);
    /**
     * Records a batch or realtime API call.
     *
     * When viaBatchApi is true:
     *   1. Computes full realtime cost via CostCalculator.
     *   2. Applies 50% discount to costUsd before persisting via SpendTracker.
     *   3. Stores a BatchAttribution linking the SpendRecord to its realtime equivalent.
     *
     * The resulting SpendRecord.costUsd reflects the actual (discounted) spend.
     */
    trackBatchUsage(params: TrackBatchParams): Promise<SpendRecord>;
    /**
     * Computes savings from Batch API usage.
     *
     * Uses attribution records (not SpendRecords) for accurate cost comparison,
     * since the SpendRecord.costUsd for batch calls reflects full token cost.
     */
    batchSavingsReport(_records: SpendRecord[], attributions: BatchAttribution[]): BatchSavingsReport;
}

/** Daily spend breakdown for a single customer. */
interface DailySpendBreakdown {
    /** YYYY-MM-DD */
    date: string;
    customerId: string;
    totalSpendUsd: number;
    callCount: number;
    /** agentId → total spend in USD */
    perAgent: Record<string, number>;
    /** modelId → total spend in USD */
    perModel: Record<string, number>;
}
/** Weekly spend breakdown for a single customer. ISO week: YYYY-Www */
interface WeeklySpendBreakdown {
    /** YYYY-Www e.g. "2026-W22" */
    week: string;
    customerId: string;
    totalSpendUsd: number;
    callCount: number;
    perAgent: Record<string, number>;
    perModel: Record<string, number>;
}
/** Monthly spend breakdown for a single customer. YYYY-MM */
interface MonthlySpendBreakdown {
    /** YYYY-MM e.g. "2026-05" */
    month: string;
    customerId: string;
    totalSpendUsd: number;
    callCount: number;
    perAgent: Record<string, number>;
    perModel: Record<string, number>;
}
/** Per-model spend stats inside a ModelSpendBreakdown. */
interface ModelSpendStats {
    totalSpendUsd: number;
    callCount: number;
    totalInputTokens: number;
    totalOutputTokens: number;
    averageCostPerCall: number;
}
/**
 * Full model spend breakdown across a record set.
 *
 * opusFraction + sonnetFraction + haikuFraction + otherFraction = 1.0
 * (all as fractions of totalSpendUsd; 0 when totalSpendUsd === 0)
 */
interface ModelSpendBreakdown {
    perModel: Record<string, ModelSpendStats>;
    totalSpendUsd: number;
    opusFraction: number;
    sonnetFraction: number;
    haikuFraction: number;
    otherFraction: number;
}
/** Per-agent daily breakdown — same shape as DailySpendBreakdown but agent-first. */
interface AgentDailySpendBreakdown {
    date: string;
    agentId: string;
    totalSpendUsd: number;
    callCount: number;
    perCustomer: Record<string, number>;
    perModel: Record<string, number>;
}
/** Per-agent monthly spend. */
interface AgentMonthlySpendBreakdown {
    month: string;
    agentId: string;
    totalSpendUsd: number;
    callCount: number;
    perCustomer: Record<string, number>;
    perModel: Record<string, number>;
}

/** Full margin report for one customer in one month, extended with tier. */
type MarginReport = CustomerMargin;
/** Tier-level margin summary aggregating all customers in a tier. */
interface TierMarginSummary {
    tierId: string;
    customerCount: number;
    avgMarginRatio: number;
    /** Count of customers whose marginRatio < targetMarginRatio. */
    customersBelowTarget: number;
    /** Count of customers whose capUtilisation > 1.0. */
    customersOverCap: number;
}

declare class PerCustomerSpendAnalyzer {
    private readonly spendStore;
    constructor(spendStore: SpendStore);
    /** Daily aggregation over a pre-fetched set of records. Pure. */
    aggregateDaily(records: SpendRecord[]): DailySpendBreakdown[];
    /** Weekly aggregation (ISO 8601 weeks). Pure. */
    aggregateWeekly(records: SpendRecord[]): WeeklySpendBreakdown[];
    /** Monthly aggregation. Pure. */
    aggregateMonthly(records: SpendRecord[]): MonthlySpendBreakdown[];
    /** Fetches records from the store and aggregates at the requested granularity. */
    loadAndAggregate(customerId: string, since: Date, until: Date, granularity: "daily" | "weekly" | "monthly"): Promise<DailySpendBreakdown[] | WeeklySpendBreakdown[] | MonthlySpendBreakdown[]>;
}

declare class PerAgentSpendAnalyzer {
    private readonly spendStore;
    constructor(spendStore: SpendStore);
    /** Daily aggregation grouped by agent. Pure. */
    aggregateDailyByAgent(records: SpendRecord[]): AgentDailySpendBreakdown[];
    /** Monthly aggregation grouped by agent. Pure. */
    aggregateMonthlyByAgent(records: SpendRecord[]): AgentMonthlySpendBreakdown[];
    /**
     * Fetches all records from the store for a given agent and time range,
     * then aggregates monthly.
     */
    loadAndAggregateByAgent(agentId: string, since: Date, until: Date): Promise<AgentMonthlySpendBreakdown[]>;
    /**
     * Fetches all records (all agents, all customers) within a window
     * and aggregates by agent monthly.
     */
    loadAllAndAggregateMonthly(since: Date, until: Date): Promise<AgentMonthlySpendBreakdown[]>;
}

declare class PerModelSpendAnalyzer {
    /**
     * Breaks down spend by model across a record set.
     * Pure — no I/O.
     */
    breakdown(records: SpendRecord[]): ModelSpendBreakdown;
}

declare class MarginMonitorAnalyzer {
    private readonly marginMonitor;
    private readonly tierStore;
    constructor(marginMonitor: MarginMonitor, tierStore: CustomerTierStore);
    /**
     * Computes margin for every customer assigned to a specific tier in a
     * given calendar month. Returns null margins filtered out.
     */
    analyzeTier(tierId: string, year: number, month: number, now?: Date): Promise<MarginReport[]>;
    /**
     * Produces a tier-level summary for every known tier in a given month.
     *
     * Runs analyzeTier for each unique tier found in the customer list, then
     * aggregates customer-level margins into tier-level statistics.
     */
    summaryByTier(year: number, month: number, now?: Date): Promise<TierMarginSummary[]>;
}

interface SpendReport {
    customerId: string;
    period: {
        year: number;
        month: number;
    };
    monthlyTotalUsd: number;
    /** agentId → total spend in USD for the period */
    perAgent: Record<string, number>;
    perModel: ModelSpendBreakdown;
    dailySeries: DailySpendBreakdown[];
    cacheHitReport: CacheHitReport;
    margin: CustomerMargin | null;
}
interface LedgerOptimisationRecommendation {
    kind: "model_swap" | "caching_opportunity" | "opus_overuse";
    description: string;
    estimatedMonthlySavingUsd: number;
    requiresApproval: true;
    detail: Record<string, unknown>;
}
interface LedgerDeps {
    spendStore: SpendStore;
    tierStore: CustomerTierStore;
    calculator: CostCalculator;
    marginMonitor?: MarginMonitor;
    anomalyDetector?: AnomalyDetector;
    perCustomer?: PerCustomerSpendAnalyzer;
    perAgent?: PerAgentSpendAnalyzer;
    perModel?: PerModelSpendAnalyzer;
    modelRecommender?: ModelRecommender;
}
declare class Ledger {
    private readonly spendStore;
    private readonly tierStore;
    private readonly calculator;
    private readonly marginMonitor;
    private readonly anomalyDetector;
    private readonly perCustomer;
    private readonly perAgent;
    private readonly perModel;
    private readonly cacheHitTracker;
    private readonly modelRecommender?;
    constructor(deps: LedgerDeps);
    /**
     * Produces a full spend report for a customer in a given month.
     *
     * Includes: monthly total, per-agent breakdown, per-model breakdown,
     * daily series, cache efficiency, and current margin snapshot.
     */
    spendReport(customerId: string, period: {
        year: number;
        month: number;
    }, now?: Date): Promise<SpendReport>;
    /**
     * Generates cost optimisation recommendations for a customer.
     *
     * Checks:
     *   1. model_swap — uses ModelRecommender on the customer's heaviest taskIntent
     *   2. caching_opportunity — cache hit ratio < 0.2 and write tokens > 50k
     *   3. opus_overuse — opusFraction > 0.3 for a customer on a tier with cap < $200
     */
    recommendOptimisations(customerId: string, period: {
        year: number;
        month: number;
    }, now?: Date): Promise<LedgerOptimisationRecommendation[]>;
    /**
     * Returns the current margin snapshot and threshold alerts for a customer.
     * Delegates to Phase A MarginMonitor.
     */
    checkMargin(customerId: string, period: {
        year: number;
        month: number;
    }, now?: Date): Promise<{
        margin: CustomerMargin | null;
        alerts: MarginAlert[];
    }>;
    /**
     * Runs anomaly detection across all records in the given time window.
     * Delegates to Phase A AnomalyDetector.
     */
    anomalyScan(period: {
        since: Date;
        until: Date;
    }, now?: Date): Promise<AnomalyDetectionResult[]>;
}

interface TallyAlert {
    id: string;
    kind: "monthly_cap_crossed" | "cache_hit_ratio_dropped" | "margin_below_floor" | "external_pricing_change";
    severity: "warning" | "critical";
    customerId?: string;
    description: string;
    observedValue?: number;
    threshold?: number;
    detectedAt: Date;
    payload: Record<string, unknown>;
}
interface TallySurfacingConfig {
    sourceName?: TriggerSourceName;
}
declare class Tally {
    private readonly marginMonitor;
    private readonly anomalyDetector;
    private readonly ledger;
    private readonly surfacingSource?;
    constructor(deps: {
        spendStore: SpendStore;
        tierStore: CustomerTierStore;
        marginMonitor: MarginMonitor;
        anomalyDetector: AnomalyDetector;
        ledger: Ledger;
        surfacingSource?: TallySurfacingConfig;
    });
    /**
     * Scans for margin threshold breaches and cache hit ratio anomalies.
     *
     * 1. Runs MarginMonitor.checkAll → converts MarginAlert → TallyAlert
     * 2. Runs AnomalyDetector.detectAll → filters to cache_hit_ratio_drop → TallyAlert
     */
    scan(period: {
        year: number;
        month: number;
    }, now?: Date): Promise<TallyAlert[]>;
    /**
     * Pure mapping — converts PricingChangeImpact[] at-risk entries to TallyAlerts.
     */
    notifyExternalPricingChange(report: PricingChangeImpact[]): TallyAlert[];
    /**
     * F0.10 adapter. Returns a TriggerSource implementation that calls scan()
     * and maps each TallyAlert to a CandidateEvent.
     *
     * Runtime: does NOT import proactive-surfacing at runtime — only uses the
     * type-only import for interface conformance. The returned object satisfies
     * the TriggerSource interface structurally.
     */
    asTriggerSource(name?: TriggerSourceName): TriggerSource;
    private marginAlertToTally;
    private anomalyToTally;
}

type index_AgentCacheStats = AgentCacheStats;
type index_AgentDailySpendBreakdown = AgentDailySpendBreakdown;
type index_AgentMonthlySpendBreakdown = AgentMonthlySpendBreakdown;
type index_AnomalyDetectionResult = AnomalyDetectionResult;
type index_AnomalyDetector = AnomalyDetector;
declare const index_AnomalyDetector: typeof AnomalyDetector;
type index_AnomalySeverity = AnomalySeverity;
type index_AnomalyThresholds = AnomalyThresholds;
type index_AnomalyType = AnomalyType;
type index_ApiCallParams = ApiCallParams;
type index_ApiCallTracker = ApiCallTracker;
declare const index_ApiCallTracker: typeof ApiCallTracker;
type index_BatchAttribution = BatchAttribution;
type index_BatchAttributionStore = BatchAttributionStore;
type index_BatchSavingsReport = BatchSavingsReport;
type index_BatchTracker = BatchTracker;
declare const index_BatchTracker: typeof BatchTracker;
type index_CacheHitReport = CacheHitReport;
type index_CacheHitTracker = CacheHitTracker;
declare const index_CacheHitTracker: typeof CacheHitTracker;
type index_CostCalculator = CostCalculator;
declare const index_CostCalculator: typeof CostCalculator;
type index_CostCalculatorConfig = CostCalculatorConfig;
type index_CustomerMargin = CustomerMargin;
type index_CustomerTier = CustomerTier;
type index_CustomerTierStore = CustomerTierStore;
declare const index_DEFAULT_OCR_COST_PER_PAGE: typeof DEFAULT_OCR_COST_PER_PAGE;
declare const index_DEFAULT_PRICING: typeof DEFAULT_PRICING;
declare const index_DEFAULT_QUALITY_MODEL_MAP: typeof DEFAULT_QUALITY_MODEL_MAP;
type index_DailySpendBreakdown = DailySpendBreakdown;
type index_DefaultSpendTracker = DefaultSpendTracker;
declare const index_DefaultSpendTracker: typeof DefaultSpendTracker;
type index_InMemoryBatchAttributionStore = InMemoryBatchAttributionStore;
declare const index_InMemoryBatchAttributionStore: typeof InMemoryBatchAttributionStore;
type index_InMemoryCustomerTierStore = InMemoryCustomerTierStore;
declare const index_InMemoryCustomerTierStore: typeof InMemoryCustomerTierStore;
type index_InMemoryOcrUsageStore = InMemoryOcrUsageStore;
declare const index_InMemoryOcrUsageStore: typeof InMemoryOcrUsageStore;
type index_InMemorySpendStore = InMemorySpendStore;
declare const index_InMemorySpendStore: typeof InMemorySpendStore;
type index_Ledger = Ledger;
declare const index_Ledger: typeof Ledger;
type index_LedgerDeps = LedgerDeps;
type index_LedgerOptimisationRecommendation = LedgerOptimisationRecommendation;
type index_MarginAlert = MarginAlert;
type index_MarginMonitor = MarginMonitor;
declare const index_MarginMonitor: typeof MarginMonitor;
type index_MarginMonitorAnalyzer = MarginMonitorAnalyzer;
declare const index_MarginMonitorAnalyzer: typeof MarginMonitorAnalyzer;
type index_MarginMonitorConfig = MarginMonitorConfig;
type index_MarginReport = MarginReport;
type index_ModelId = ModelId;
type index_ModelPricing = ModelPricing;
type index_ModelRecommendation = ModelRecommendation;
type index_ModelRecommender = ModelRecommender;
declare const index_ModelRecommender: typeof ModelRecommender;
type index_ModelRecommenderConfig = ModelRecommenderConfig;
type index_ModelSpendBreakdown = ModelSpendBreakdown;
type index_ModelSpendStats = ModelSpendStats;
type index_MonthlySpendBreakdown = MonthlySpendBreakdown;
declare const index_OPUS_MODEL_PATTERN: typeof OPUS_MODEL_PATTERN;
type index_OcrCostDifferentialReport = OcrCostDifferentialReport;
type index_OcrProvider = OcrProvider;
type index_OcrTracker = OcrTracker;
declare const index_OcrTracker: typeof OcrTracker;
type index_OcrTrackerConfig = OcrTrackerConfig;
type index_OcrUsageRecord = OcrUsageRecord;
type index_OcrUsageStore = OcrUsageStore;
type index_PerAgentSpendAnalyzer = PerAgentSpendAnalyzer;
declare const index_PerAgentSpendAnalyzer: typeof PerAgentSpendAnalyzer;
type index_PerCustomerSpendAnalyzer = PerCustomerSpendAnalyzer;
declare const index_PerCustomerSpendAnalyzer: typeof PerCustomerSpendAnalyzer;
type index_PerModelSpendAnalyzer = PerModelSpendAnalyzer;
declare const index_PerModelSpendAnalyzer: typeof PerModelSpendAnalyzer;
type index_PricingChangeAdapter = PricingChangeAdapter;
declare const index_PricingChangeAdapter: typeof PricingChangeAdapter;
type index_PricingChangeAdapterConfig = PricingChangeAdapterConfig;
type index_PricingChangeImpact = PricingChangeImpact;
type index_ProviderCostSummary = ProviderCostSummary;
type index_QualityModelMap = QualityModelMap;
type index_QualityRequirement = QualityRequirement;
type index_RecordParams = RecordParams;
type index_SimpleLogger = SimpleLogger;
type index_SpendRecord = SpendRecord;
type index_SpendReport = SpendReport;
type index_SpendStore = SpendStore;
type index_SpendTracker = SpendTracker;
type index_Tally = Tally;
declare const index_Tally: typeof Tally;
type index_TallyAlert = TallyAlert;
type index_TallySurfacingConfig = TallySurfacingConfig;
type index_TaskIntent = TaskIntent;
type index_TaskSignature = TaskSignature;
type index_TierMarginSummary = TierMarginSummary;
type index_TrackBatchParams = TrackBatchParams;
type index_TrackOcrParams = TrackOcrParams;
type index_WeeklySpendBreakdown = WeeklySpendBreakdown;
type index_WorkflowCacheStats = WorkflowCacheStats;
declare namespace index {
  export { type index_AgentCacheStats as AgentCacheStats, type index_AgentDailySpendBreakdown as AgentDailySpendBreakdown, type index_AgentMonthlySpendBreakdown as AgentMonthlySpendBreakdown, type index_AnomalyDetectionResult as AnomalyDetectionResult, index_AnomalyDetector as AnomalyDetector, type index_AnomalySeverity as AnomalySeverity, type index_AnomalyThresholds as AnomalyThresholds, type index_AnomalyType as AnomalyType, type index_ApiCallParams as ApiCallParams, index_ApiCallTracker as ApiCallTracker, type index_BatchAttribution as BatchAttribution, type index_BatchAttributionStore as BatchAttributionStore, type index_BatchSavingsReport as BatchSavingsReport, index_BatchTracker as BatchTracker, type index_CacheHitReport as CacheHitReport, index_CacheHitTracker as CacheHitTracker, index_CostCalculator as CostCalculator, type index_CostCalculatorConfig as CostCalculatorConfig, type index_CustomerMargin as CustomerMargin, type index_CustomerTier as CustomerTier, type index_CustomerTierStore as CustomerTierStore, index_DEFAULT_OCR_COST_PER_PAGE as DEFAULT_OCR_COST_PER_PAGE, index_DEFAULT_PRICING as DEFAULT_PRICING, index_DEFAULT_QUALITY_MODEL_MAP as DEFAULT_QUALITY_MODEL_MAP, type index_DailySpendBreakdown as DailySpendBreakdown, index_DefaultSpendTracker as DefaultSpendTracker, index_InMemoryBatchAttributionStore as InMemoryBatchAttributionStore, index_InMemoryCustomerTierStore as InMemoryCustomerTierStore, index_InMemoryOcrUsageStore as InMemoryOcrUsageStore, index_InMemorySpendStore as InMemorySpendStore, index_Ledger as Ledger, type index_LedgerDeps as LedgerDeps, type index_LedgerOptimisationRecommendation as LedgerOptimisationRecommendation, type index_MarginAlert as MarginAlert, index_MarginMonitor as MarginMonitor, index_MarginMonitorAnalyzer as MarginMonitorAnalyzer, type index_MarginMonitorConfig as MarginMonitorConfig, type index_MarginReport as MarginReport, type index_ModelId as ModelId, type index_ModelPricing as ModelPricing, type index_ModelRecommendation as ModelRecommendation, index_ModelRecommender as ModelRecommender, type index_ModelRecommenderConfig as ModelRecommenderConfig, type index_ModelSpendBreakdown as ModelSpendBreakdown, type index_ModelSpendStats as ModelSpendStats, type index_MonthlySpendBreakdown as MonthlySpendBreakdown, index_OPUS_MODEL_PATTERN as OPUS_MODEL_PATTERN, type index_OcrCostDifferentialReport as OcrCostDifferentialReport, type index_OcrProvider as OcrProvider, index_OcrTracker as OcrTracker, type index_OcrTrackerConfig as OcrTrackerConfig, type index_OcrUsageRecord as OcrUsageRecord, type index_OcrUsageStore as OcrUsageStore, index_PerAgentSpendAnalyzer as PerAgentSpendAnalyzer, index_PerCustomerSpendAnalyzer as PerCustomerSpendAnalyzer, index_PerModelSpendAnalyzer as PerModelSpendAnalyzer, index_PricingChangeAdapter as PricingChangeAdapter, type index_PricingChangeAdapterConfig as PricingChangeAdapterConfig, type index_PricingChangeImpact as PricingChangeImpact, type index_ProviderCostSummary as ProviderCostSummary, type index_QualityModelMap as QualityModelMap, type index_QualityRequirement as QualityRequirement, type index_RecordParams as RecordParams, type index_SimpleLogger as SimpleLogger, type index_SpendRecord as SpendRecord, type index_SpendReport as SpendReport, type index_SpendStore as SpendStore, type index_SpendTracker as SpendTracker, index_Tally as Tally, type index_TallyAlert as TallyAlert, type index_TallySurfacingConfig as TallySurfacingConfig, type index_TaskIntent as TaskIntent, type index_TaskSignature as TaskSignature, type index_TierMarginSummary as TierMarginSummary, type index_TrackBatchParams as TrackBatchParams, type index_TrackOcrParams as TrackOcrParams, type index_WeeklySpendBreakdown as WeeklySpendBreakdown, type index_WorkflowCacheStats as WorkflowCacheStats };
}

export { PerAgentSpendAnalyzer as $, type AgentCacheStats as A, type BatchAttribution as B, type CacheHitReport as C, DEFAULT_OCR_COST_PER_PAGE as D, type LedgerOptimisationRecommendation as E, MarginMonitor as F, MarginMonitorAnalyzer as G, type MarginMonitorConfig as H, InMemoryBatchAttributionStore as I, type MarginReport as J, type ModelId as K, Ledger as L, type MarginAlert as M, type ModelPricing as N, type ModelRecommendation as O, ModelRecommender as P, type ModelRecommenderConfig as Q, type ModelSpendBreakdown as R, type ModelSpendStats as S, type MonthlySpendBreakdown as T, OPUS_MODEL_PATTERN as U, type OcrCostDifferentialReport as V, type OcrProvider as W, OcrTracker as X, type OcrTrackerConfig as Y, type OcrUsageRecord as Z, type OcrUsageStore as _, type AgentDailySpendBreakdown as a, PerCustomerSpendAnalyzer as a0, PerModelSpendAnalyzer as a1, PricingChangeAdapter as a2, type PricingChangeAdapterConfig as a3, type PricingChangeImpact as a4, type ProviderCostSummary as a5, type QualityModelMap as a6, type QualityRequirement as a7, type RecordParams as a8, type SimpleLogger as a9, type SpendRecord as aa, type SpendReport as ab, type SpendStore as ac, type SpendTracker as ad, Tally as ae, type TallyAlert as af, type TallySurfacingConfig as ag, type TaskIntent as ah, type TaskSignature as ai, type TierMarginSummary as aj, type TrackBatchParams as ak, type TrackOcrParams as al, type WeeklySpendBreakdown as am, type WorkflowCacheStats as an, index as ao, type AgentMonthlySpendBreakdown as b, type AnomalyDetectionResult as c, AnomalyDetector as d, type AnomalySeverity as e, type AnomalyThresholds as f, type AnomalyType as g, type ApiCallParams as h, ApiCallTracker as i, type BatchAttributionStore as j, type BatchSavingsReport as k, BatchTracker as l, CacheHitTracker as m, CostCalculator as n, type CostCalculatorConfig as o, type CustomerMargin as p, type CustomerTier as q, type CustomerTierStore as r, DEFAULT_PRICING as s, DEFAULT_QUALITY_MODEL_MAP as t, type DailySpendBreakdown as u, DefaultSpendTracker as v, InMemoryCustomerTierStore as w, InMemoryOcrUsageStore as x, InMemorySpendStore as y, type LedgerDeps as z };
