import { x as AIToolCall, y as AITool, e as AIChatResponse, w as AIMessage, c as IAI, I as ICache, a as ILogger, d as AIChatRequest, b as ITracing, K as ISpan, D as AIUsageInfo, f as AIStreamChunk, g as AIStreamCallback, h as AICompletionRequest, i as AICompletionResponse, j as AIEmbeddingRequest, k as AIEmbeddingResponse, l as AIModelConfig, m as AIModelType, n as AIProvider } from './IAI-D8wA_i8N.js';

/**
 * IAIUsage - Per-tenant AI token tracking and cost allocation
 *
 * Provides infrastructure for:
 * - Token usage tracking per tenant
 * - Cost allocation and budgeting
 * - Usage quotas and limits
 * - Billing integration
 * - Analytics and reporting
 */
type UsageCategory = "chat" | "completion" | "embedding" | "image" | "audio" | "video" | "fine_tuning";
type UsageInterval = "minute" | "hour" | "day" | "week" | "month" | "year";
interface UsageRecord {
    id: string;
    /** Tenant ID */
    tenantId: string;
    /** User ID (optional, for per-user tracking) */
    userId?: string;
    /** API key ID (optional) */
    apiKeyId?: string;
    /** Usage category */
    category: UsageCategory;
    /** AI provider */
    provider: string;
    /** Model used */
    model: string;
    /** Input tokens */
    inputTokens: number;
    /** Output tokens */
    outputTokens: number;
    /** Total tokens */
    totalTokens: number;
    /** Cost in USD */
    costUsd: number;
    /** Request latency in ms */
    latencyMs: number;
    /** Request ID for tracing */
    requestId?: string;
    /** Whether the request succeeded */
    success: boolean;
    /** Error message if failed */
    error?: string;
    /** Additional metadata */
    metadata?: Record<string, unknown>;
    /** Created timestamp */
    createdAt: Date;
}
type QuotaType = "tokens" | "requests" | "cost";
interface Quota {
    id: string;
    /** Tenant ID */
    tenantId: string;
    /** Quota type */
    type: QuotaType;
    /** Category (or 'all' for global quota) */
    category: UsageCategory | "all";
    /** Quota limit */
    limit: number;
    /** Quota period */
    period: UsageInterval;
    /** Current usage */
    used: number;
    /** Period start date */
    periodStart: Date;
    /** Period end date */
    periodEnd: Date;
    /** Action when quota exceeded */
    action: "block" | "warn" | "notify" | "overage";
    /** Overage rate (for 'overage' action) */
    overageRate?: number;
    /** Alert thresholds (percentages) */
    alertThresholds?: number[];
    /** Whether quota is enabled */
    enabled: boolean;
}
interface QuotaStatus {
    quota: Quota;
    /** Current usage */
    used: number;
    /** Remaining */
    remaining: number;
    /** Usage percentage */
    percentUsed: number;
    /** Whether quota is exceeded */
    exceeded: boolean;
    /** Estimated time until reset */
    resetsIn?: number;
    /** Alerts triggered */
    alertsTriggered: number[];
}
interface Budget {
    id: string;
    /** Tenant ID */
    tenantId: string;
    /** Budget name */
    name: string;
    /** Budget amount in USD */
    amount: number;
    /** Budget period */
    period: UsageInterval;
    /** Categories included in budget */
    categories?: UsageCategory[];
    /** Current spend */
    spent: number;
    /** Period start date */
    periodStart: Date;
    /** Period end date */
    periodEnd: Date;
    /** Alert thresholds (percentages) */
    alertThresholds: number[];
    /** Action when budget exceeded */
    action: "block" | "warn" | "notify";
    /** Whether budget is enabled */
    enabled: boolean;
}
interface BudgetStatus {
    budget: Budget;
    /** Current spend */
    spent: number;
    /** Remaining */
    remaining: number;
    /** Spend percentage */
    percentSpent: number;
    /** Whether budget is exceeded */
    exceeded: boolean;
    /** Projected spend for full period */
    projected: number;
    /** Alerts triggered */
    alertsTriggered: number[];
}
interface UsageInvoiceItem {
    category: UsageCategory;
    provider: string;
    model: string;
    inputTokens: number;
    outputTokens: number;
    totalTokens: number;
    requests: number;
    costUsd: number;
}
interface UsageInvoice {
    id: string;
    tenantId: string;
    periodStart: Date;
    periodEnd: Date;
    items: UsageInvoiceItem[];
    subtotal: number;
    discounts?: Array<{
        type: string;
        amount: number;
        description?: string;
    }>;
    total: number;
    currency: string;
    status: "draft" | "pending" | "paid" | "overdue";
    dueDate?: Date;
    paidAt?: Date;
    createdAt: Date;
}
interface UsageSummary {
    tenantId: string;
    period: {
        start: Date;
        end: Date;
        interval: UsageInterval;
    };
    totals: {
        inputTokens: number;
        outputTokens: number;
        totalTokens: number;
        requests: number;
        successfulRequests: number;
        failedRequests: number;
        costUsd: number;
        averageLatencyMs: number;
    };
    byCategory: Record<UsageCategory, {
        inputTokens: number;
        outputTokens: number;
        totalTokens: number;
        requests: number;
        costUsd: number;
    }>;
    byModel: Record<string, {
        inputTokens: number;
        outputTokens: number;
        totalTokens: number;
        requests: number;
        costUsd: number;
    }>;
    byUser?: Record<string, {
        inputTokens: number;
        outputTokens: number;
        totalTokens: number;
        requests: number;
        costUsd: number;
    }>;
}
interface UsageTrend {
    tenantId: string;
    period: {
        start: Date;
        end: Date;
        interval: UsageInterval;
    };
    dataPoints: Array<{
        timestamp: Date;
        inputTokens: number;
        outputTokens: number;
        totalTokens: number;
        requests: number;
        costUsd: number;
    }>;
    growth: {
        tokens: number;
        requests: number;
        cost: number;
    };
}
interface CostBreakdown {
    tenantId: string;
    period: {
        start: Date;
        end: Date;
    };
    total: number;
    byProvider: Record<string, number>;
    byModel: Record<string, number>;
    byCategory: Record<UsageCategory, number>;
    byUser?: Record<string, number>;
}
interface UsageQuery {
    tenantId: string;
    startDate?: Date;
    endDate?: Date;
    category?: UsageCategory | UsageCategory[];
    provider?: string | string[];
    model?: string | string[];
    userId?: string;
    success?: boolean;
    limit?: number;
    offset?: number;
    sortBy?: "createdAt" | "totalTokens" | "costUsd" | "latencyMs";
    sortOrder?: "asc" | "desc";
}
interface UsageQueryResult {
    records: UsageRecord[];
    total: number;
    aggregations: {
        totalTokens: number;
        totalCost: number;
        averageLatency: number;
    };
}
type AlertType = "quota_warning" | "quota_exceeded" | "budget_warning" | "budget_exceeded" | "anomaly";
interface UsageAlert {
    id: string;
    tenantId: string;
    type: AlertType;
    severity: "info" | "warning" | "critical";
    message: string;
    metadata: {
        quotaId?: string;
        budgetId?: string;
        threshold?: number;
        currentValue?: number;
        limit?: number;
    };
    acknowledged: boolean;
    acknowledgedAt?: Date;
    acknowledgedBy?: string;
    createdAt: Date;
}
interface AIUsageConfig {
    /** Enable usage tracking */
    enabled?: boolean;
    /** Default quota period */
    defaultQuotaPeriod?: UsageInterval;
    /** Default budget period */
    defaultBudgetPeriod?: UsageInterval;
    /** Enable per-user tracking */
    trackPerUser?: boolean;
    /** Enable anomaly detection */
    enableAnomalyDetection?: boolean;
    /** Anomaly threshold (standard deviations) */
    anomalyThreshold?: number;
    /** Cost precision (decimal places) */
    costPrecision?: number;
    /** Retention period in days */
    retentionDays?: number;
}
/**
 * IAIUsage - AI usage tracking interface
 *
 * @example
 * ```typescript
 * const usage = platform.aiUsage;
 *
 * // Record usage after AI call
 * await usage.record({
 *   tenantId: 'tenant_123',
 *   category: 'chat',
 *   provider: 'openai',
 *   model: 'gpt-4',
 *   inputTokens: 150,
 *   outputTokens: 300,
 *   totalTokens: 450,
 *   costUsd: 0.018,
 *   latencyMs: 1200,
 *   success: true,
 * });
 *
 * // Check quota before making request
 * const quotaStatus = await usage.checkQuota('tenant_123', 'tokens', 'chat');
 * if (quotaStatus.exceeded) {
 *   throw new Error('Token quota exceeded');
 * }
 *
 * // Get usage summary
 * const summary = await usage.getSummary('tenant_123', 'month');
 * console.log(`Total cost: $${summary.totals.costUsd}`);
 * ```
 */
interface IAIUsage {
    /**
     * Record a usage event
     */
    record(record: Omit<UsageRecord, "id" | "createdAt">): Promise<UsageRecord>;
    /**
     * Record multiple usage events (batch)
     */
    recordBatch(records: Array<Omit<UsageRecord, "id" | "createdAt">>): Promise<UsageRecord[]>;
    /**
     * Query usage records
     */
    query(query: UsageQuery): Promise<UsageQueryResult>;
    /**
     * Get a specific usage record
     */
    getRecord(recordId: string): Promise<UsageRecord | null>;
    /**
     * Create or update a quota
     */
    setQuota(quota: Omit<Quota, "id" | "used" | "periodStart" | "periodEnd">): Promise<Quota>;
    /**
     * Get a quota
     */
    getQuota(tenantId: string, type: QuotaType, category: UsageCategory | "all"): Promise<Quota | null>;
    /**
     * List quotas for a tenant
     */
    listQuotas(tenantId: string): Promise<Quota[]>;
    /**
     * Check quota status
     */
    checkQuota(tenantId: string, type: QuotaType, category: UsageCategory | "all"): Promise<QuotaStatus>;
    /**
     * Check all quotas for a tenant
     */
    checkAllQuotas(tenantId: string): Promise<QuotaStatus[]>;
    /**
     * Delete a quota
     */
    deleteQuota(quotaId: string): Promise<void>;
    /**
     * Reset quota usage (admin only)
     */
    resetQuota(quotaId: string): Promise<Quota>;
    /**
     * Create or update a budget
     */
    setBudget(budget: Omit<Budget, "id" | "spent" | "periodStart" | "periodEnd">): Promise<Budget>;
    /**
     * Get a budget
     */
    getBudget(budgetId: string): Promise<Budget | null>;
    /**
     * List budgets for a tenant
     */
    listBudgets(tenantId: string): Promise<Budget[]>;
    /**
     * Check budget status
     */
    checkBudget(budgetId: string): Promise<BudgetStatus>;
    /**
     * Check all budgets for a tenant
     */
    checkAllBudgets(tenantId: string): Promise<BudgetStatus[]>;
    /**
     * Delete a budget
     */
    deleteBudget(budgetId: string): Promise<void>;
    /**
     * Get usage summary for a tenant
     */
    getSummary(tenantId: string, period: UsageInterval, date?: Date): Promise<UsageSummary>;
    /**
     * Get usage trends
     */
    getTrends(tenantId: string, period: UsageInterval, dataPoints?: number): Promise<UsageTrend>;
    /**
     * Get cost breakdown
     */
    getCostBreakdown(tenantId: string, startDate: Date, endDate: Date): Promise<CostBreakdown>;
    /**
     * Compare usage between periods
     */
    comparePeriods(tenantId: string, period1Start: Date, period1End: Date, period2Start: Date, period2End: Date): Promise<{
        period1: UsageSummary;
        period2: UsageSummary;
        changes: {
            tokens: number;
            requests: number;
            cost: number;
            latency: number;
        };
    }>;
    /**
     * Generate invoice for a period
     */
    generateInvoice(tenantId: string, periodStart: Date, periodEnd: Date): Promise<UsageInvoice>;
    /**
     * Get an invoice
     */
    getInvoice(invoiceId: string): Promise<UsageInvoice | null>;
    /**
     * List invoices for a tenant
     */
    listInvoices(tenantId: string, options?: {
        status?: UsageInvoice["status"];
        limit?: number;
        offset?: number;
    }): Promise<{
        invoices: UsageInvoice[];
        total: number;
    }>;
    /**
     * Mark invoice as paid
     */
    markInvoicePaid(invoiceId: string): Promise<UsageInvoice>;
    /**
     * Get alerts for a tenant
     */
    getAlerts(tenantId: string, options?: {
        type?: AlertType;
        acknowledged?: boolean;
        limit?: number;
    }): Promise<UsageAlert[]>;
    /**
     * Acknowledge an alert
     */
    acknowledgeAlert(alertId: string, acknowledgedBy?: string): Promise<void>;
    /**
     * Acknowledge all alerts for a tenant
     */
    acknowledgeAllAlerts(tenantId: string, acknowledgedBy?: string): Promise<number>;
    /**
     * Estimate cost for a request
     */
    estimateCost(provider: string, model: string, inputTokens: number, outputTokens: number): Promise<number>;
    /**
     * Get token pricing for models
     */
    getPricing(): Promise<Record<string, Record<string, {
        inputPer1K: number;
        outputPer1K: number;
    }>>>;
    /**
     * Project usage for remainder of period
     */
    projectUsage(tenantId: string, period: UsageInterval): Promise<{
        projected: {
            tokens: number;
            cost: number;
            requests: number;
        };
        confidence: number;
    }>;
}
/**
 * MemoryAIUsage - In-memory implementation for testing
 */
declare class MemoryAIUsage implements IAIUsage {
    private config;
    private records;
    private quotas;
    private budgets;
    private invoices;
    private alerts;
    private pricing;
    constructor(config?: AIUsageConfig);
    record(record: Omit<UsageRecord, "id" | "createdAt">): Promise<UsageRecord>;
    recordBatch(records: Array<Omit<UsageRecord, "id" | "createdAt">>): Promise<UsageRecord[]>;
    query(query: UsageQuery): Promise<UsageQueryResult>;
    getRecord(recordId: string): Promise<UsageRecord | null>;
    setQuota(quota: Omit<Quota, "id" | "used" | "periodStart" | "periodEnd">): Promise<Quota>;
    getQuota(tenantId: string, type: QuotaType, category: UsageCategory | "all"): Promise<Quota | null>;
    listQuotas(tenantId: string): Promise<Quota[]>;
    checkQuota(tenantId: string, type: QuotaType, category: UsageCategory | "all"): Promise<QuotaStatus>;
    checkAllQuotas(tenantId: string): Promise<QuotaStatus[]>;
    deleteQuota(quotaId: string): Promise<void>;
    resetQuota(quotaId: string): Promise<Quota>;
    setBudget(budget: Omit<Budget, "id" | "spent" | "periodStart" | "periodEnd">): Promise<Budget>;
    getBudget(budgetId: string): Promise<Budget | null>;
    listBudgets(tenantId: string): Promise<Budget[]>;
    checkBudget(budgetId: string): Promise<BudgetStatus>;
    checkAllBudgets(tenantId: string): Promise<BudgetStatus[]>;
    deleteBudget(budgetId: string): Promise<void>;
    getSummary(tenantId: string, period: UsageInterval, date?: Date): Promise<UsageSummary>;
    getTrends(tenantId: string, period: UsageInterval, dataPoints?: number): Promise<UsageTrend>;
    getCostBreakdown(tenantId: string, startDate: Date, endDate: Date): Promise<CostBreakdown>;
    comparePeriods(tenantId: string, period1Start: Date, period1End: Date, period2Start: Date, period2End: Date): Promise<{
        period1: UsageSummary;
        period2: UsageSummary;
        changes: {
            tokens: number;
            requests: number;
            cost: number;
            latency: number;
        };
    }>;
    generateInvoice(tenantId: string, periodStart: Date, periodEnd: Date): Promise<UsageInvoice>;
    getInvoice(invoiceId: string): Promise<UsageInvoice | null>;
    listInvoices(tenantId: string, options?: {
        status?: UsageInvoice["status"];
        limit?: number;
        offset?: number;
    }): Promise<{
        invoices: UsageInvoice[];
        total: number;
    }>;
    markInvoicePaid(invoiceId: string): Promise<UsageInvoice>;
    getAlerts(tenantId: string, options?: {
        type?: AlertType;
        acknowledged?: boolean;
        limit?: number;
    }): Promise<UsageAlert[]>;
    acknowledgeAlert(alertId: string, acknowledgedBy?: string): Promise<void>;
    acknowledgeAllAlerts(tenantId: string, acknowledgedBy?: string): Promise<number>;
    estimateCost(provider: string, model: string, inputTokens: number, outputTokens: number): Promise<number>;
    getPricing(): Promise<Record<string, Record<string, {
        inputPer1K: number;
        outputPer1K: number;
    }>>>;
    projectUsage(tenantId: string, period: UsageInterval): Promise<{
        projected: {
            tokens: number;
            cost: number;
            requests: number;
        };
        confidence: number;
    }>;
    private updateQuotaUsage;
    private updateBudgetSpend;
    private createAlert;
    private getPeriodBounds;
    private getIntervalMs;
    private getSummaryForPeriod;
}

/**
 * Agent Loop — Multi-turn tool-calling orchestration
 *
 * Runs an IAI chat → tool execution → repeat loop until the AI stops,
 * a budget is hit, or the caller aborts.
 */

/**
 * Function that executes a tool call and returns a string result.
 * Receives the parsed arguments (from JSON) and the raw tool call.
 */
type ToolExecutor = (args: Record<string, unknown>, toolCall: AIToolCall) => Promise<string>;
/**
 * Tool definition paired with its executor.
 */
interface AgentTool {
    /** The AI tool definition (JSON Schema for the function) */
    definition: AITool;
    /** The function that executes this tool */
    execute: ToolExecutor;
}
/**
 * Result of a single tool call execution.
 */
interface AgentToolResult {
    /** The original tool call from the AI */
    toolCall: AIToolCall;
    /** The string result returned by the executor */
    result: string;
    /** Whether the tool execution succeeded */
    success: boolean;
    /** Error message if the tool failed */
    error?: string;
    /** Execution duration in ms */
    durationMs: number;
    /** Whether the result came from cache */
    cached: boolean;
}
/**
 * Cumulative usage across all iterations.
 */
interface AgentCumulativeUsage {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
    estimatedCostUsd: number;
    iterations: number;
    toolCallCount: number;
}
/**
 * Event emitted after each iteration of the agent loop.
 */
interface AgentIterationEvent {
    /** 1-based iteration number */
    iteration: number;
    /** The AI response for this iteration */
    response: AIChatResponse;
    /** Tool calls made in this iteration (empty if no tool calls) */
    toolCalls: AgentToolResult[];
    /** Cumulative usage across all iterations */
    cumulativeUsage: AgentCumulativeUsage;
    /** Full conversation so far */
    messages: AIMessage[];
}
/**
 * Callback invoked after each iteration.
 * Return `false` to abort the loop.
 */
type AgentIterationCallback = (event: AgentIterationEvent) => void | false | Promise<void | false>;
/**
 * Why the agent loop stopped.
 */
type AgentStopReason = "stop" | "max_iterations" | "max_tokens" | "max_cost" | "aborted" | "callback_abort" | "length" | "content_filter" | "error";
/**
 * Options for runAgentLoop.
 */
interface AgentLoopOptions {
    /** The IAI instance to call */
    ai: IAI;
    /** Initial messages (system + user prompt) */
    messages: AIMessage[];
    /** Tool definitions with executors */
    tools: AgentTool[];
    /** Maximum iterations before forced stop @default 10 */
    maxIterations: number;
    /** Maximum cumulative total tokens @default Infinity */
    maxTokens: number;
    /** Maximum cumulative cost in USD @default Infinity */
    maxCostUsd: number;
    /** Optional cache for tool results */
    cache?: ICache;
    /** Cache TTL in seconds for tool results @default 300 */
    cacheTtlSeconds: number;
    /** Cache key prefix @default "agent:tool:" */
    cacheKeyPrefix: string;
    /** Callback after each iteration */
    onIteration?: AgentIterationCallback;
    /** AbortSignal for cancellation */
    signal?: AbortSignal;
    /** Logger for observability */
    logger?: ILogger;
    /** Additional fields for AIChatRequest (model, temperature, etc.) */
    chatRequestOverrides?: Partial<Omit<AIChatRequest, "messages" | "tools">>;
}
/**
 * Result of a completed agent loop.
 */
interface AgentLoopResult {
    /** Final AI response */
    response: AIChatResponse;
    /** Complete conversation history including all tool messages */
    messages: AIMessage[];
    /** Why the loop stopped */
    stopReason: AgentStopReason;
    /** Per-iteration details */
    iterations: AgentIterationEvent[];
    /** Cumulative usage summary */
    usage: AgentCumulativeUsage;
}
declare const DEFAULT_AGENT_LOOP_OPTIONS: Pick<AgentLoopOptions, "maxIterations" | "maxTokens" | "maxCostUsd" | "cacheTtlSeconds" | "cacheKeyPrefix">;
/**
 * Run a multi-turn tool-calling agent loop.
 *
 * @example
 * ```typescript
 * const result = await runAgentLoop({
 *   ai: platform.ai,
 *   messages: [
 *     { role: 'system', content: 'You are a helpful assistant.' },
 *     { role: 'user', content: 'What is the weather in London?' },
 *   ],
 *   tools: [{
 *     definition: {
 *       type: 'function',
 *       function: {
 *         name: 'get_weather',
 *         description: 'Get the weather for a city',
 *         parameters: { type: 'object', properties: { city: { type: 'string' } } },
 *       },
 *     },
 *     execute: async (args) => {
 *       const weather = await fetchWeather(args.city as string);
 *       return JSON.stringify(weather);
 *     },
 *   }],
 * });
 *
 * console.log(result.stopReason); // "stop"
 * console.log(result.usage.totalTokens); // cumulative tokens
 * ```
 */
declare function runAgentLoop(options: Partial<AgentLoopOptions> & Pick<AgentLoopOptions, "ai" | "messages" | "tools">): Promise<AgentLoopResult>;

/**
 * Agent Tracer — OTEL span helpers for agent observability
 *
 * Wraps ITracing with standardized agent-specific span attributes
 * following OpenTelemetry semantic conventions.
 */

interface AgentTracerOptions {
    /** The ITracing instance */
    tracing: ITracing;
    /** Agent identifier for span attributes */
    agentId: string;
}
interface AgentTracer {
    /**
     * Wrap an entire agent loop execution in a span.
     * Sets `agent.id` on the span.
     */
    traceLoop<T>(fn: (span: ISpan) => Promise<T>): Promise<T>;
    /**
     * Wrap a single iteration in a span.
     * Sets `agent.iteration` on the span.
     */
    traceIteration(iteration: number, fn: (span: ISpan) => Promise<void>): Promise<void>;
    /**
     * Wrap a single tool call execution in a span.
     * Sets `agent.tool.name`, `agent.tool.duration_ms`, `agent.tool.success`, `agent.tool.cached`.
     */
    traceToolCall(toolName: string, fn: (span: ISpan) => Promise<AgentToolResult>): Promise<AgentToolResult>;
    /**
     * Record a decision event on the current span.
     */
    traceDecision(span: ISpan, attrs: {
        finishReason: string;
        toolCallCount: number;
        cumulativeUsage: AgentCumulativeUsage;
    }): void;
}
/**
 * Create an agent tracer with standardized OTEL attributes.
 *
 * @example
 * ```typescript
 * const tracer = createAgentTracer({ tracing: platform.tracing, agentId: 'weather-agent' });
 *
 * const result = await tracer.traceLoop(async (span) => {
 *   return await runAgentLoop({ ... });
 * });
 * ```
 */
declare function createAgentTracer(options: AgentTracerOptions): AgentTracer;

/**
 * Agent Usage Tracker — Per-agent cost tracking via IAIUsage
 *
 * Tags usage records with agentId in metadata for per-agent attribution.
 * No changes to IAIUsage interface required.
 */

interface AgentUsageTrackerOptions {
    /** The IAIUsage instance */
    usage: IAIUsage;
    /** Agent identifier to tag on all records */
    agentId: string;
    /** Tenant ID for usage records */
    tenantId: string;
    /** Optional user ID */
    userId?: string;
}
interface AgentUsageRecordParams {
    /** AI provider name */
    provider: string;
    /** Model used */
    model: string;
    /** Token usage info from the AI response */
    usage: AIUsageInfo;
    /** Usage category @default "chat" */
    category?: UsageCategory;
    /** Whether the request succeeded @default true */
    success?: boolean;
    /** Request latency in ms */
    latencyMs?: number;
    /** Error message if failed */
    error?: string;
}
interface AgentBudget {
    /** Maximum cumulative cost in USD */
    maxCostUsd?: number;
    /** Maximum cumulative tokens */
    maxTokens?: number;
}
interface AgentUsageTracker {
    /**
     * Record a single AI call's usage, tagged with agentId in metadata.
     */
    recordIteration(params: AgentUsageRecordParams): Promise<UsageRecord>;
    /**
     * Returns an AgentIterationCallback suitable for runAgentLoop's onIteration.
     * Records usage for each iteration and returns false when budget is exceeded.
     */
    createBudgetCallback(budget?: AgentBudget): AgentIterationCallback;
}
/**
 * Create a usage tracker that tags all records with an agent ID.
 *
 * @example
 * ```typescript
 * const tracker = createAgentUsageTracker({
 *   usage: platform.aiUsage,
 *   agentId: 'weather-agent',
 *   tenantId: 'tenant_123',
 * });
 *
 * const result = await runAgentLoop({
 *   ai, messages, tools,
 *   onIteration: tracker.createBudgetCallback({ maxCostUsd: 0.50 }),
 * });
 * ```
 */
declare function createAgentUsageTracker(options: AgentUsageTrackerOptions): AgentUsageTracker;

/**
 * Traced AI — Auto-instrument any IAI with OTEL spans
 *
 * Wraps an IAI instance so that every chat() call is automatically
 * wrapped in an OTEL span capturing provider, model, tokens, cost,
 * latency, and finish reason.
 */

interface TracedAIOptions {
    /** The IAI instance to wrap */
    ai: IAI;
    /** The ITracing instance */
    tracing: ITracing;
}
/**
 * Wraps an IAI instance with automatic OTEL tracing on chat operations.
 *
 * @example
 * ```typescript
 * const tracedAI = createTracedAI({ ai: platform.ai, tracing: platform.tracing });
 *
 * // Every chat() call now creates an OTEL span with ai.* attributes
 * const response = await tracedAI.chat({ messages: [...] });
 * ```
 */
declare function createTracedAI(options: TracedAIOptions): IAI;

/**
 * Ollama Adapter — Local LLM inference via Ollama REST API
 *
 * Zero API cost. Runs against a local Ollama instance.
 * Supports chat, completion, and embedding operations.
 *
 * @example
 * ```typescript
 * import { OllamaAdapter } from '@digilogiclabs/platform-core';
 *
 * const ai = new OllamaAdapter({ baseUrl: 'http://localhost:11434' });
 * const response = await ai.chat({
 *   messages: [{ role: 'user', content: 'Hello' }],
 *   model: 'qwen2.5:3b',
 * });
 * ```
 */

interface OllamaAdapterConfig {
    /** Ollama API base URL @default "http://localhost:11434" */
    baseUrl?: string;
    /** Default chat model @default "qwen2.5:3b" */
    defaultModel?: string;
    /** Default embedding model @default "nomic-embed-text" */
    defaultEmbeddingModel?: string;
    /** Request timeout in ms @default 120000 */
    timeoutMs?: number;
}
declare class OllamaAdapter implements IAI {
    private readonly baseUrl;
    private readonly defaultModel;
    private readonly defaultEmbeddingModel;
    private readonly timeoutMs;
    constructor(config?: OllamaAdapterConfig);
    chat(request: AIChatRequest): Promise<AIChatResponse>;
    chatStream(request: AIChatRequest): AsyncIterable<AIStreamChunk>;
    chatWithCallback(request: AIChatRequest, callback: AIStreamCallback): Promise<AIChatResponse>;
    complete(request: AICompletionRequest): Promise<AICompletionResponse>;
    completeStream(request: AICompletionRequest): AsyncIterable<AIStreamChunk>;
    embed(request: AIEmbeddingRequest): Promise<AIEmbeddingResponse>;
    similarity(text1: string, text2: string, model?: string): Promise<number>;
    listModels(): Promise<AIModelConfig[]>;
    getModel(modelId: string): Promise<AIModelConfig | null>;
    supportsCapability(modelId: string, capability: AIModelType): Promise<boolean>;
    estimateTokens(text: string, _model?: string): Promise<number>;
    estimateCost(): Promise<number>;
    healthCheck(): Promise<{
        healthy: boolean;
        providers: Record<AIProvider, {
            available: boolean;
            latencyMs?: number;
            error?: string;
        }>;
    }>;
    private fetch;
}

export { type AIUsageConfig as A, type Budget as B, type CostBreakdown as C, DEFAULT_AGENT_LOOP_OPTIONS as D, type AgentUsageTrackerOptions as E, type AgentUsageRecordParams as F, type AgentBudget as G, type AgentUsageTracker as H, type IAIUsage as I, createAgentUsageTracker as J, type TracedAIOptions as K, createTracedAI as L, MemoryAIUsage as M, OllamaAdapter as O, type Quota as Q, type ToolExecutor as T, type UsageRecord as U, type UsageQuery as a, type UsageQueryResult as b, type QuotaType as c, type UsageCategory as d, type QuotaStatus as e, type BudgetStatus as f, type UsageInterval as g, type UsageSummary as h, type UsageTrend as i, type UsageInvoice as j, type AlertType as k, type UsageAlert as l, type UsageInvoiceItem as m, type OllamaAdapterConfig as n, type AgentTool as o, type AgentToolResult as p, type AgentCumulativeUsage as q, type AgentIterationEvent as r, type AgentIterationCallback as s, type AgentStopReason as t, type AgentLoopOptions as u, type AgentLoopResult as v, runAgentLoop as w, type AgentTracerOptions as x, type AgentTracer as y, createAgentTracer as z };
