@sovr/engine 3.2.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,3 +1,1204 @@
1
+ /**
2
+ * @sovr/engine — Expression Tree Engine
3
+ *
4
+ * Compiles SOVR Policy DSL rules into an AST (Abstract Syntax Tree),
5
+ * supporting complex condition composition, short-circuit evaluation,
6
+ * and high-performance cached execution.
7
+ *
8
+ * Features:
9
+ * - Nested AND/OR/NOT logic
10
+ * - Comparison operators: ==, !=, >, <, >=, <=, in, not_in, contains, starts_with, ends_with, matches
11
+ * - Variable references (dot-separated paths from context)
12
+ * - Built-in functions (now_hour, risk_level, is_business_hours, etc.)
13
+ * - Compile once, evaluate many times
14
+ *
15
+ * @since 3.3.0
16
+ */
17
+ type ExpressionNode = LogicalNode | ComparisonNode | NotNode | LiteralNode | VariableNode | FunctionNode;
18
+ interface LogicalNode {
19
+ type: 'AND' | 'OR';
20
+ children: ExpressionNode[];
21
+ }
22
+ interface NotNode {
23
+ type: 'NOT';
24
+ child: ExpressionNode;
25
+ }
26
+ interface ComparisonNode {
27
+ type: 'COMPARE';
28
+ operator: '==' | '!=' | '>' | '<' | '>=' | '<=' | 'in' | 'not_in' | 'contains' | 'starts_with' | 'ends_with' | 'matches';
29
+ left: ExpressionNode;
30
+ right: ExpressionNode;
31
+ }
32
+ interface LiteralNode {
33
+ type: 'LITERAL';
34
+ value: string | number | boolean | string[] | number[];
35
+ }
36
+ interface VariableNode {
37
+ type: 'VARIABLE';
38
+ path: string;
39
+ }
40
+ interface FunctionNode {
41
+ type: 'FUNCTION';
42
+ name: string;
43
+ args: ExpressionNode[];
44
+ }
45
+ interface EvalContext {
46
+ [key: string]: any;
47
+ }
48
+ interface CompiledExpression {
49
+ ast: ExpressionNode;
50
+ evaluate: (ctx: EvalContext) => boolean;
51
+ toString: () => string;
52
+ variables: string[];
53
+ }
54
+ /**
55
+ * Compile a JSON rule definition into an expression tree.
56
+ *
57
+ * Supported JSON formats:
58
+ * ```json
59
+ * { "and": [...conditions] }
60
+ * { "or": [...conditions] }
61
+ * { "not": condition }
62
+ * { "field": "action.type", "op": "==", "value": "delete" }
63
+ * { "field": "risk_score", "op": ">", "value": 0.8 }
64
+ * { "field": "user.role", "op": "in", "value": ["admin", "owner"] }
65
+ * { "fn": "now_hour", "op": ">=", "value": 22 }
66
+ * ```
67
+ */
68
+ declare function compileFromJSON(rule: any): CompiledExpression;
69
+ /**
70
+ * Register a custom function for use in expression trees.
71
+ */
72
+ declare function registerFunction(name: string, fn: (args: any[], ctx: EvalContext) => any): void;
73
+ interface ExprTreePolicyRule {
74
+ id: string;
75
+ name: string;
76
+ priority: number;
77
+ condition: any;
78
+ action: 'ALLOW' | 'DENY' | 'REQUIRE_APPROVAL' | 'LOG';
79
+ metadata?: Record<string, any>;
80
+ }
81
+ interface RuleEvalResult {
82
+ ruleId: string;
83
+ ruleName: string;
84
+ matched: boolean;
85
+ action: string;
86
+ evaluationTimeMs: number;
87
+ }
88
+ declare function compileRuleSet(rules: ExprTreePolicyRule[]): void;
89
+ /**
90
+ * Evaluate all rules against a context (sorted by priority, first match wins).
91
+ */
92
+ declare function evaluateRules(rules: ExprTreePolicyRule[], ctx: EvalContext): {
93
+ matched: ExprTreePolicyRule | null;
94
+ results: RuleEvalResult[];
95
+ };
96
+
97
+ /**
98
+ * @sovr/engine — Adaptive Threshold Module
99
+ *
100
+ * Automatically adjusts risk-control thresholds based on historical decision data:
101
+ * - Sliding window statistics (false positive rate, false negative rate, pass rate)
102
+ * - EWMA (Exponentially Weighted Moving Average) threshold self-adjustment
103
+ * - Safety boundary protection (thresholds never exceed [min, max] range)
104
+ * - Change audit (every adjustment is logged via callback)
105
+ *
106
+ * This module is database-agnostic — it uses in-memory storage and emits
107
+ * adjustment events via a configurable callback for external persistence.
108
+ *
109
+ * @since 3.3.0
110
+ */
111
+ interface ThresholdConfig {
112
+ /** Threshold name (e.g., risk_score, cost_limit, latency_p99) */
113
+ name: string;
114
+ /** Current value */
115
+ currentValue: number;
116
+ /** Minimum allowed value (safety lower bound) */
117
+ minValue: number;
118
+ /** Maximum allowed value (safety upper bound) */
119
+ maxValue: number;
120
+ /** EWMA smoothing factor (0 < alpha < 1), higher = more responsive */
121
+ alpha: number;
122
+ /** Maximum adjustment step per cycle (percentage) */
123
+ maxStepPercent: number;
124
+ /** Last adjustment timestamp */
125
+ lastAdjustedAt: number;
126
+ /** Direction lock (prevents oscillation) */
127
+ directionLock: 'up' | 'down' | null;
128
+ /** Consecutive same-direction adjustment count */
129
+ consecutiveAdjustments: number;
130
+ }
131
+ interface DecisionFeedback {
132
+ /** Decision ID */
133
+ decisionId: string;
134
+ /** Threshold name */
135
+ thresholdName: string;
136
+ /** Threshold value at decision time */
137
+ thresholdAtDecision: number;
138
+ /** Actual risk score */
139
+ actualScore: number;
140
+ /** Decision outcome */
141
+ outcome: 'true_positive' | 'true_negative' | 'false_positive' | 'false_negative';
142
+ /** Timestamp */
143
+ timestamp: number;
144
+ }
145
+ interface AdjustmentResult {
146
+ thresholdName: string;
147
+ previousValue: number;
148
+ newValue: number;
149
+ reason: string;
150
+ metrics: {
151
+ falsePositiveRate: number;
152
+ falseNegativeRate: number;
153
+ totalSamples: number;
154
+ windowHours: number;
155
+ };
156
+ }
157
+ interface AdaptiveThresholdOptions {
158
+ /** Custom threshold configurations (overrides defaults) */
159
+ thresholds?: ThresholdConfig[];
160
+ /** Maximum feedback buffer size */
161
+ maxBufferSize?: number;
162
+ /** Cooldown between adjustments in milliseconds */
163
+ adjustmentCooldownMs?: number;
164
+ /** Callback for audit trail (called on every adjustment) */
165
+ onAdjustment?: (result: AdjustmentResult) => void | Promise<void>;
166
+ }
167
+ declare class AdaptiveThresholdManager {
168
+ private thresholds;
169
+ private feedbackBuffer;
170
+ private maxBufferSize;
171
+ private cooldownMs;
172
+ private onAdjustment?;
173
+ constructor(options?: AdaptiveThresholdOptions);
174
+ /** Get a threshold by name */
175
+ getThreshold(name: string): ThresholdConfig | undefined;
176
+ /** Get all thresholds */
177
+ getAllThresholds(): ThresholdConfig[];
178
+ /** Record a decision feedback sample */
179
+ recordFeedback(feedback: DecisionFeedback): void;
180
+ /**
181
+ * Adjust a single threshold based on feedback (EWMA algorithm).
182
+ * Returns null if no adjustment is needed (cooldown, insufficient samples, etc.).
183
+ */
184
+ adjustThreshold(thresholdName: string, windowHours?: number): Promise<AdjustmentResult | null>;
185
+ /** Adjust all thresholds */
186
+ adjustAll(windowHours?: number): Promise<AdjustmentResult[]>;
187
+ /** Manually override a threshold value */
188
+ setThresholdManual(name: string, value: number): boolean;
189
+ /** Get feedback statistics for a threshold (or all) */
190
+ getFeedbackStats(thresholdName?: string, windowHours?: number): {
191
+ total: number;
192
+ truePositive: number;
193
+ trueNegative: number;
194
+ falsePositive: number;
195
+ falseNegative: number;
196
+ accuracy: number;
197
+ precision: number;
198
+ recall: number;
199
+ };
200
+ /** Clear the feedback buffer */
201
+ clearFeedback(): void;
202
+ }
203
+
204
+ /**
205
+ * @sovr/engine — Feature Switches Module
206
+ *
207
+ * Manages 4 core feature switches for the SOVR decision plane:
208
+ * - USE_NEW_RISK_ENGINE: Enable expression tree + adaptive threshold engine
209
+ * - ENFORCE_COST_CAP: Hard-reject when agent cost exceeds budget
210
+ * - ENABLE_PROMPT_GUARD: Enable prompt injection scanning for all LLM calls
211
+ * - DISABLE_EVIDENCE_PAUSE: Keep evidence chain writing even under high load
212
+ *
213
+ * All switches are stored in-memory with configurable persistence callbacks.
214
+ * Supports multi-tenant isolation and TTL-based caching.
215
+ *
216
+ * @since 3.3.0
217
+ */
218
+ interface FeatureSwitchDef {
219
+ key: string;
220
+ description: string;
221
+ defaultValue: boolean;
222
+ category: 'risk' | 'cost' | 'security' | 'evidence';
223
+ impactLevel: 'high' | 'medium' | 'low';
224
+ }
225
+ interface FeatureSwitchState {
226
+ key: string;
227
+ value: boolean;
228
+ description: string;
229
+ category: string;
230
+ impactLevel: string;
231
+ isDefault: boolean;
232
+ }
233
+ interface FeatureSwitchesOptions {
234
+ /** Cache TTL in milliseconds (default: 30000) */
235
+ cacheTtlMs?: number;
236
+ /** Callback to load switch value from external storage */
237
+ onLoad?: (key: string, tenantId: string) => Promise<boolean | null>;
238
+ /** Callback to save switch value to external storage */
239
+ onSave?: (key: string, value: boolean, tenantId: string) => Promise<void>;
240
+ }
241
+ declare const SOVR_FEATURE_SWITCHES: Record<string, FeatureSwitchDef>;
242
+ declare class FeatureSwitchesManager {
243
+ private cache;
244
+ private cacheTtlMs;
245
+ private onLoad?;
246
+ private onSave?;
247
+ constructor(options?: FeatureSwitchesOptions);
248
+ /**
249
+ * Get a switch value (with cache + optional external load).
250
+ */
251
+ getValue(key: string, tenantId?: string): Promise<boolean>;
252
+ /**
253
+ * Set a switch value (updates cache + optional external save).
254
+ */
255
+ setValue(key: string, value: boolean, tenantId?: string): Promise<void>;
256
+ /**
257
+ * Get all switch states.
258
+ */
259
+ getAll(tenantId?: string): Promise<Record<string, FeatureSwitchState>>;
260
+ /** Clear the cache (for testing or forced refresh) */
261
+ clearCache(): void;
262
+ isNewRiskEngineEnabled(tenantId?: string): Promise<boolean>;
263
+ isCostCapEnforced(tenantId?: string): Promise<boolean>;
264
+ isPromptGuardEnabled(tenantId?: string): Promise<boolean>;
265
+ isEvidencePauseDisabled(tenantId?: string): Promise<boolean>;
266
+ }
267
+
268
+ /**
269
+ * @sovr/engine — Pricing Rules Engine
270
+ *
271
+ * Evaluates pricing rules for SOVR-governed actions.
272
+ * Supports tiered pricing, volume discounts, time-based multipliers,
273
+ * and cost-cap enforcement.
274
+ *
275
+ * Schema reference (sovr_pricing_rules table):
276
+ * id, rule_name, tier, action_pattern, base_cost_usd, multiplier,
277
+ * volume_discount_threshold, volume_discount_percent, time_window_start,
278
+ * time_window_end, is_active, priority, created_at, updated_at
279
+ *
280
+ * This module is database-agnostic — rules are loaded into memory
281
+ * and evaluated purely in-process.
282
+ *
283
+ * @since 3.3.0
284
+ */
285
+ interface PricingRule {
286
+ id: string;
287
+ ruleName: string;
288
+ /** Which tier this rule applies to (empty string = all tiers) */
289
+ tier: string;
290
+ /** Glob pattern for action names */
291
+ actionPattern: string;
292
+ /** Base cost in USD */
293
+ baseCostUsd: number;
294
+ /** Cost multiplier (default 1.0) */
295
+ multiplier: number;
296
+ /** Volume discount threshold (number of actions) */
297
+ volumeDiscountThreshold: number;
298
+ /** Volume discount percentage (0-100) */
299
+ volumeDiscountPercent: number;
300
+ /** Time window start hour (0-23, -1 = no time restriction) */
301
+ timeWindowStart: number;
302
+ /** Time window end hour (0-23, -1 = no time restriction) */
303
+ timeWindowEnd: number;
304
+ /** Whether this rule is active */
305
+ isActive: boolean;
306
+ /** Priority (higher = evaluated first) */
307
+ priority: number;
308
+ }
309
+ interface PricingEvalRequest {
310
+ /** Action being performed */
311
+ action: string;
312
+ /** Actor's tier */
313
+ tier: string;
314
+ /** Number of actions already performed in current period */
315
+ currentVolume: number;
316
+ /** Current hour (0-23), defaults to now */
317
+ currentHour?: number;
318
+ }
319
+ interface PricingEvalResult {
320
+ /** Final computed cost in USD */
321
+ costUsd: number;
322
+ /** Base cost before adjustments */
323
+ baseCostUsd: number;
324
+ /** Applied multiplier */
325
+ multiplier: number;
326
+ /** Volume discount applied (0-100) */
327
+ volumeDiscountPercent: number;
328
+ /** Whether a time-based rule was applied */
329
+ timeWindowActive: boolean;
330
+ /** Which rule was matched */
331
+ matchedRuleId: string | null;
332
+ /** Human-readable breakdown */
333
+ breakdown: string;
334
+ }
335
+ declare class PricingRulesEngine {
336
+ private rules;
337
+ constructor(rules?: PricingRule[]);
338
+ /** Load rules (sorted by priority descending) */
339
+ loadRules(rules: PricingRule[]): void;
340
+ /** Add a single rule */
341
+ addRule(rule: PricingRule): void;
342
+ /** Get all loaded rules */
343
+ getRules(): readonly PricingRule[];
344
+ /**
345
+ * Evaluate pricing for an action.
346
+ * Returns the computed cost and breakdown.
347
+ */
348
+ evaluate(request: PricingEvalRequest): PricingEvalResult;
349
+ private globMatch;
350
+ }
351
+
352
+ /**
353
+ * @sovr/engine — Recalculation Engine (Pure Memory Mode)
354
+ *
355
+ * Aggregation layer recalculation capabilities:
356
+ * - G3: Recalculation triggers (manual/automatic)
357
+ * - G4: Consistency verification (compare pre/post values)
358
+ * - G5: Incremental recalculation (from checkpoint)
359
+ * - G6: Recalculation audit (via onAudit callback)
360
+ *
361
+ * Zero external dependencies. Audit via callback injection.
362
+ */
363
+ type RecalcTaskStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
364
+ type RecalcTriggerType = 'manual' | 'scheduled' | 'drift_detected' | 'data_correction' | 'policy_change';
365
+ type RecalcGranularity = '5m' | '1h' | '1d' | 'all';
366
+ interface RecalcTask {
367
+ id: string;
368
+ tenantId: string;
369
+ triggerType: RecalcTriggerType;
370
+ triggeredBy: string;
371
+ reason: string;
372
+ fromTs: number;
373
+ toTs: number;
374
+ granularity: RecalcGranularity;
375
+ incremental: boolean;
376
+ incrementalCheckpoint?: string;
377
+ status: RecalcTaskStatus;
378
+ startedAt?: number;
379
+ completedAt?: number;
380
+ progress: number;
381
+ bucketsProcessed: number;
382
+ rowsUpserted: number;
383
+ consistencyResult?: ConsistencyResult;
384
+ error?: string;
385
+ createdAt: number;
386
+ traceId: string;
387
+ }
388
+ interface ConsistencyResult {
389
+ id: string;
390
+ taskId: string;
391
+ status: 'consistent' | 'inconsistent' | 'partial';
392
+ totalComparisons: number;
393
+ matchCount: number;
394
+ mismatchCount: number;
395
+ consistencyRate: number;
396
+ mismatches: ConsistencyMismatch[];
397
+ verifiedAt: number;
398
+ verificationHash: string;
399
+ }
400
+ interface ConsistencyMismatch {
401
+ metric: string;
402
+ bucket: string;
403
+ currentValue: number;
404
+ recalculatedValue: number;
405
+ deviation: number;
406
+ deviationPercent: number;
407
+ severity: 'low' | 'medium' | 'high' | 'critical';
408
+ }
409
+ interface AggregateSnapshot {
410
+ id: string;
411
+ tenantId: string;
412
+ snapshotType: 'pre_recalc' | 'post_recalc' | 'scheduled';
413
+ taskId?: string;
414
+ metrics: Record<string, number>;
415
+ hash: string;
416
+ createdAt: number;
417
+ }
418
+ type RecalcHandler = (task: RecalcTask) => Promise<{
419
+ bucketsProcessed: number;
420
+ rowsUpserted: number;
421
+ metrics: Record<string, number>;
422
+ }>;
423
+ interface RecalcEngineConfig {
424
+ maxRangeDays: number;
425
+ onAudit?: (event: {
426
+ type: string;
427
+ details: Record<string, unknown>;
428
+ timestamp: number;
429
+ }) => void;
430
+ }
431
+ declare class RecalculationEngine {
432
+ private tasks;
433
+ private consistencyResults;
434
+ private snapshots;
435
+ private handlers;
436
+ private config;
437
+ constructor(config?: Partial<RecalcEngineConfig>);
438
+ /** G3: Trigger recalculation */
439
+ triggerRecalculation(input: {
440
+ tenantId: string;
441
+ triggerType: RecalcTriggerType;
442
+ triggeredBy: string;
443
+ reason: string;
444
+ fromTs: number;
445
+ toTs: number;
446
+ granularity?: RecalcGranularity;
447
+ incremental?: boolean;
448
+ incrementalCheckpoint?: string;
449
+ }): RecalcTask;
450
+ /** Execute recalculation task */
451
+ executeTask(taskId: string): Promise<RecalcTask>;
452
+ /** G4: Verify consistency */
453
+ verifyConsistency(taskId: string, preSnapshot: AggregateSnapshot, postSnapshot: AggregateSnapshot, recalculatedMetrics?: Record<string, number>): ConsistencyResult;
454
+ /** G5: Incremental recalculation */
455
+ triggerIncremental(input: {
456
+ tenantId: string;
457
+ triggeredBy: string;
458
+ reason: string;
459
+ granularity?: RecalcGranularity;
460
+ }): RecalcTask;
461
+ /** Create aggregate snapshot */
462
+ createSnapshot(tenantId: string, snapshotType: AggregateSnapshot['snapshotType'], taskId?: string, metrics?: Record<string, number>): AggregateSnapshot;
463
+ /** Register recalculation handler */
464
+ registerHandler(granularity: RecalcGranularity, handler: RecalcHandler): void;
465
+ /** Query functions */
466
+ getTask(taskId: string): RecalcTask | undefined;
467
+ getTasks(tenantId: string, limit?: number): RecalcTask[];
468
+ getConsistencyResult(taskId: string): ConsistencyResult | undefined;
469
+ getSnapshot(snapshotId: string): AggregateSnapshot | undefined;
470
+ cancelTask(taskId: string): boolean;
471
+ private audit;
472
+ }
473
+ declare function createRecalculationEngine(config?: Partial<RecalcEngineConfig>): RecalculationEngine;
474
+
475
+ /**
476
+ * @sovr/engine — AutoHarden Module (Pure Memory Mode)
477
+ *
478
+ * Automatic security hardening when adversarial threats detected:
479
+ * - B7: Auto-harden capability
480
+ * - Gate level upgrade, rate limit reduction, enhanced audit
481
+ * - Configurable measures with auto-rollback
482
+ *
483
+ * Zero external dependencies. Audit via callback injection.
484
+ */
485
+ type HardenLevel = 'normal' | 'elevated' | 'hardened' | 'lockdown';
486
+ type HardenMeasureType = 'gate_level_upgrade' | 'rate_limit_reduce' | 'enhanced_audit' | 'ip_block' | 'session_invalidate' | 'feature_disable' | 'alert_admin';
487
+ interface HardenMeasure {
488
+ id: string;
489
+ type: HardenMeasureType;
490
+ description: string;
491
+ applied: boolean;
492
+ appliedAt?: number;
493
+ rolledBackAt?: number;
494
+ }
495
+ interface HardenEvent {
496
+ id: string;
497
+ tenantId: string;
498
+ triggeredBy: string;
499
+ reason: string;
500
+ previousLevel: HardenLevel;
501
+ newLevel: HardenLevel;
502
+ measures: HardenMeasure[];
503
+ createdAt: number;
504
+ rolledBack: boolean;
505
+ rolledBackAt?: number;
506
+ traceId: string;
507
+ }
508
+ interface HardenConfig {
509
+ enabled: boolean;
510
+ levelMeasures: Record<HardenLevel, HardenMeasureType[]>;
511
+ autoRollbackMs: number;
512
+ rateLimitReductionFactor: number;
513
+ notifyAdmin: boolean;
514
+ onNotifyAdmin?: (event: HardenEvent) => Promise<void>;
515
+ onAudit?: (event: {
516
+ type: string;
517
+ details: Record<string, unknown>;
518
+ timestamp: number;
519
+ }) => void;
520
+ }
521
+ interface HardenState {
522
+ currentLevel: HardenLevel;
523
+ lastEvent?: HardenEvent;
524
+ activeMeasures: HardenMeasure[];
525
+ hardenedSince?: number;
526
+ expectedRollbackAt?: number;
527
+ }
528
+ declare class AutoHardenEngine {
529
+ private states;
530
+ private history;
531
+ private config;
532
+ private rollbackTimers;
533
+ private maxHistory;
534
+ constructor(config?: Partial<HardenConfig>);
535
+ /** Get tenant harden state */
536
+ getState(tenantId: string): HardenState;
537
+ /** Get current harden level */
538
+ getLevel(tenantId: string): HardenLevel;
539
+ /** Auto-harden (main entry) */
540
+ harden(input: {
541
+ tenantId: string;
542
+ triggeredBy: string;
543
+ reason: string;
544
+ targetLevel?: HardenLevel;
545
+ manipulationScore?: number;
546
+ reasonCodes?: string[];
547
+ }): Promise<HardenEvent>;
548
+ /** Manual rollback */
549
+ rollback(tenantId: string, rolledBackBy: string, reason?: string): Promise<HardenEvent>;
550
+ /** Update config */
551
+ updateConfig(config: Partial<HardenConfig>): HardenConfig;
552
+ /** Get config */
553
+ getConfig(): HardenConfig;
554
+ /** Get history */
555
+ getHistory(tenantId?: string, limit?: number): HardenEvent[];
556
+ /** Get all active hardened states */
557
+ getActiveStates(): Array<{
558
+ tenantId: string;
559
+ state: HardenState;
560
+ }>;
561
+ /** Cleanup timers */
562
+ destroy(): void;
563
+ private determineLevel;
564
+ private applyMeasures;
565
+ private getMeasureDescription;
566
+ private scheduleAutoRollback;
567
+ private audit;
568
+ }
569
+ declare function createAutoHardenEngine(config?: Partial<HardenConfig>): AutoHardenEngine;
570
+
571
+ /**
572
+ * SOVR Cost Estimator
573
+ * 成本预估精确化引擎 — 补齐 F3 缺口
574
+ *
575
+ * 功能:
576
+ * 1. Token 级成本预估(基于模型定价表)
577
+ * 2. 工具调用成本预估
578
+ * 3. 人工审批成本预估(基于费率)
579
+ * 4. 总成本预估(模型 + 工具 + 人工)
580
+ * 5. 预估准确度追踪
581
+ *
582
+ * 设计原则:
583
+ * - 模型定价表可配置、可更新
584
+ * - 支持多种计费模式(按 token、按调用、按时间)
585
+ * - 预估结果包含置信区间
586
+ * - 与 CostGate 协作
587
+ */
588
+ /** 模型定价 */
589
+ interface ModelPricing {
590
+ /** 模型 ID */
591
+ modelId: string;
592
+ /** 模型名称 */
593
+ modelName: string;
594
+ /** 输入 token 单价(美元/1K tokens) */
595
+ inputPricePerKToken: number;
596
+ /** 输出 token 单价(美元/1K tokens) */
597
+ outputPricePerKToken: number;
598
+ /** 缓存 token 单价(如有) */
599
+ cachedInputPricePerKToken?: number;
600
+ /** 最大上下文长度 */
601
+ maxContextLength: number;
602
+ /** 最后更新 */
603
+ updatedAt: Date;
604
+ }
605
+ /** 工具定价 */
606
+ interface ToolPricing {
607
+ /** 工具 ID */
608
+ toolId: string;
609
+ /** 工具名称 */
610
+ toolName: string;
611
+ /** 每次调用成本(美元) */
612
+ costPerCall: number;
613
+ /** 乘算因子(如有额外成本) */
614
+ multiplier: number;
615
+ /** 最后更新 */
616
+ updatedAt: Date;
617
+ }
618
+ /** 成本预估请求 */
619
+ interface CostEstimateRequest {
620
+ /** 模型 ID */
621
+ modelId: string;
622
+ /** 预估输入 token 数 */
623
+ estimatedInputTokens: number;
624
+ /** 预估输出 token 数 */
625
+ estimatedOutputTokens: number;
626
+ /** 工具调用列表 */
627
+ toolCalls?: Array<{
628
+ toolId: string;
629
+ estimatedCalls: number;
630
+ }>;
631
+ /** 是否需要人工审批 */
632
+ requiresHumanReview?: boolean;
633
+ /** 人工审批级别 */
634
+ humanReviewLevel?: 'standard' | 'senior' | 'executive';
635
+ }
636
+ /** 成本预估结果 */
637
+ interface CostEstimate {
638
+ /** 预估 ID */
639
+ id: string;
640
+ /** 模型成本 */
641
+ modelCost: {
642
+ inputCost: number;
643
+ outputCost: number;
644
+ total: number;
645
+ };
646
+ /** 工具成本 */
647
+ toolCost: {
648
+ items: Array<{
649
+ toolId: string;
650
+ calls: number;
651
+ costPerCall: number;
652
+ total: number;
653
+ }>;
654
+ total: number;
655
+ };
656
+ /** 人工审批成本 */
657
+ humanCost: {
658
+ level: string;
659
+ hourlyRate: number;
660
+ estimatedMinutes: number;
661
+ total: number;
662
+ } | null;
663
+ /** 总成本 */
664
+ totalCost: number;
665
+ /** 置信区间 */
666
+ confidence: {
667
+ low: number;
668
+ high: number;
669
+ level: number;
670
+ };
671
+ /** 预估时间 */
672
+ estimatedAt: Date;
673
+ }
674
+ /** 预估准确度记录 */
675
+ interface EstimateAccuracy {
676
+ estimateId: string;
677
+ estimatedCost: number;
678
+ actualCost: number;
679
+ deviation: number;
680
+ deviationPercent: number;
681
+ recordedAt: Date;
682
+ }
683
+ /**
684
+ * 预估成本
685
+ */
686
+ declare function estimateCost(request: CostEstimateRequest): CostEstimate;
687
+ /**
688
+ * 记录实际成本(用于准确度追踪)
689
+ */
690
+ declare function recordActualCost(estimateId: string, actualCost: number): EstimateAccuracy | null;
691
+ /**
692
+ * 更新模型定价
693
+ */
694
+ declare function updateModelPricing(pricing: ModelPricing): void;
695
+ /**
696
+ * 更新工具定价
697
+ */
698
+ declare function updateToolPricing(pricing: ToolPricing): void;
699
+ /**
700
+ * 获取模型定价表
701
+ */
702
+ declare function getModelPricingTable(): ModelPricing[];
703
+ /**
704
+ * 获取工具定价表
705
+ */
706
+ declare function getToolPricingTable(): ToolPricing[];
707
+ /**
708
+ * 获取预估准确度统计
709
+ */
710
+ declare function getAccuracyStats(): {
711
+ totalRecords: number;
712
+ avgDeviation: number;
713
+ avgDeviationPercent: number;
714
+ confidenceLevel: number;
715
+ };
716
+
717
+ /**
718
+ * server/sovr/semanticDriftDetector.ts
719
+ *
720
+ * 语义漂移检测器 — 补齐 K10 缺口
721
+ *
722
+ * 功能:
723
+ * - 策略语义指纹计算(基于规则结构的哈希)
724
+ * - 版本间语义差异检测
725
+ * - 漂移评分(0-1,0=完全一致,1=完全不同)
726
+ * - 漂移告警(超过阈值时触发)
727
+ * - 漂移审计链
728
+ *
729
+ * 设计原则:纯逻辑模块,无外部依赖
730
+ */
731
+ interface SemanticFingerprint {
732
+ version: string;
733
+ hash: string;
734
+ ruleCount: number;
735
+ allowCount: number;
736
+ denyCount: number;
737
+ reviewCount: number;
738
+ resourceSet: string[];
739
+ actionSet: string[];
740
+ conditionDepth: number;
741
+ timestamp: number;
742
+ }
743
+ interface DriftResult {
744
+ fromVersion: string;
745
+ toVersion: string;
746
+ driftScore: number;
747
+ ruleCountDelta: number;
748
+ addedRules: string[];
749
+ removedRules: string[];
750
+ modifiedRules: string[];
751
+ decisionChanges: {
752
+ ruleId: string;
753
+ from: string;
754
+ to: string;
755
+ }[];
756
+ newResources: string[];
757
+ removedResources: string[];
758
+ severity: 'none' | 'low' | 'medium' | 'high' | 'critical';
759
+ timestamp: number;
760
+ }
761
+ interface PolicySnapshot {
762
+ version: string;
763
+ rules: PolicyRuleForDrift[];
764
+ metadata?: Record<string, unknown>;
765
+ }
766
+ interface PolicyRuleForDrift {
767
+ id: string;
768
+ action: string;
769
+ resource: string;
770
+ decision: 'ALLOW' | 'DENY' | 'REVIEW';
771
+ conditions?: Record<string, unknown>;
772
+ priority: number;
773
+ }
774
+ interface DriftConfig {
775
+ lowThreshold: number;
776
+ mediumThreshold: number;
777
+ highThreshold: number;
778
+ criticalThreshold: number;
779
+ onDriftDetected?: (result: DriftResult) => void;
780
+ onAudit?: (event: {
781
+ type: string;
782
+ details: Record<string, unknown>;
783
+ timestamp: number;
784
+ }) => void;
785
+ }
786
+ declare class SemanticDriftDetectorEngine {
787
+ private fingerprints;
788
+ private history;
789
+ private config;
790
+ constructor(config?: Partial<DriftConfig>);
791
+ /**
792
+ * 计算策略语义指纹
793
+ */
794
+ computeFingerprint(snapshot: PolicySnapshot): SemanticFingerprint;
795
+ /**
796
+ * 检测两个版本间的语义漂移
797
+ */
798
+ detectDrift(from: PolicySnapshot, to: PolicySnapshot): DriftResult;
799
+ /**
800
+ * 获取漂移历史
801
+ */
802
+ getDriftHistory(): DriftResult[];
803
+ /**
804
+ * 获取指纹
805
+ */
806
+ getFingerprint(version: string): SemanticFingerprint | null;
807
+ /**
808
+ * 获取漂移趋势
809
+ */
810
+ getDriftTrend(): {
811
+ version: string;
812
+ driftScore: number;
813
+ timestamp: number;
814
+ }[];
815
+ private hashRules;
816
+ private ruleChanged;
817
+ private maxConditionDepth;
818
+ private objectDepth;
819
+ }
820
+ declare function createSemanticDriftDetector(config?: Partial<DriftConfig>): SemanticDriftDetectorEngine;
821
+
822
+ /**
823
+ * server/sovr/costGateEnhanced.ts
824
+ *
825
+ * 经济约束层增强 — 补齐 E2/E4/E5/E6/E7/E9/E10 缺口
826
+ *
827
+ * 功能:
828
+ * - E2: 成本汇总表(1h/24h/7d 滑动窗口)
829
+ * - E4: BUDGET_EXCEEDED 标准原因码
830
+ * - E5: 成本超限审计事件
831
+ * - E6: Cockpit 成本仪表板数据源
832
+ * - E7: getDailyCostStats API
833
+ * - E9: 工具调用成本代理(按工具计费)
834
+ * - E10: 人工审批时成本计算
835
+ *
836
+ * 设计原则:纯逻辑模块,审计通过回调注入
837
+ */
838
+ interface CostRecord {
839
+ id: string;
840
+ tenantId: string;
841
+ agentId: string;
842
+ action: string;
843
+ toolName?: string;
844
+ costUsd: number;
845
+ tokenCount?: number;
846
+ modelName?: string;
847
+ timestamp: number;
848
+ category: CostCategory;
849
+ metadata?: Record<string, unknown>;
850
+ }
851
+ type CostCategory = 'llm_inference' | 'tool_call' | 'human_review' | 'storage' | 'network' | 'compute' | 'other';
852
+ interface CostSummary {
853
+ period: '1h' | '24h' | '7d' | '30d';
854
+ totalCostUsd: number;
855
+ byCategory: Record<CostCategory, number>;
856
+ byAgent: Record<string, number>;
857
+ byTool: Record<string, number>;
858
+ recordCount: number;
859
+ avgCostPerAction: number;
860
+ peakHour?: number;
861
+ startTime: number;
862
+ endTime: number;
863
+ }
864
+ interface DailyCostStats {
865
+ date: string;
866
+ totalCostUsd: number;
867
+ byCategory: Record<CostCategory, number>;
868
+ actionCount: number;
869
+ uniqueAgents: number;
870
+ budgetUtilization: number;
871
+ }
872
+ interface BudgetExceededEvent {
873
+ code: 'BUDGET_EXCEEDED';
874
+ tenantId: string;
875
+ agentId: string;
876
+ action: string;
877
+ currentCostUsd: number;
878
+ budgetLimitUsd: number;
879
+ overage: number;
880
+ period: string;
881
+ timestamp: number;
882
+ severity: 'warning' | 'critical' | 'blocked';
883
+ }
884
+ interface ToolCostConfig {
885
+ toolName: string;
886
+ baseCostUsd: number;
887
+ perCallCostUsd: number;
888
+ perTokenCostUsd?: number;
889
+ maxCostPerCallUsd?: number;
890
+ }
891
+ interface HumanReviewCost {
892
+ reviewId: string;
893
+ reviewerType: 'human' | 'escalated';
894
+ waitTimeMs: number;
895
+ reviewTimeMs: number;
896
+ costUsd: number;
897
+ hourlyRateUsd: number;
898
+ }
899
+ interface CostGateEnhancedConfig {
900
+ defaultBudgetUsd: number;
901
+ warningThreshold: number;
902
+ criticalThreshold: number;
903
+ humanReviewHourlyRateUsd: number;
904
+ toolCosts: ToolCostConfig[];
905
+ onAudit?: (event: CostAuditEvent) => void;
906
+ onBudgetExceeded?: (event: BudgetExceededEvent) => void;
907
+ }
908
+ interface CostAuditEvent {
909
+ type: 'cost_recorded' | 'budget_warning' | 'budget_critical' | 'budget_exceeded' | 'summary_generated';
910
+ tenantId: string;
911
+ details: Record<string, unknown>;
912
+ timestamp: number;
913
+ }
914
+ declare class CostGateEnhancedEngine {
915
+ private records;
916
+ private budgets;
917
+ private config;
918
+ private toolCostMap;
919
+ constructor(config?: Partial<CostGateEnhancedConfig>);
920
+ /**
921
+ * E2: 记录成本并生成汇总
922
+ */
923
+ recordCost(record: CostRecord): BudgetExceededEvent | null;
924
+ /**
925
+ * E2: 获取成本汇总(滑动窗口)
926
+ */
927
+ getCostSummary(tenantId: string, period: CostSummary['period']): CostSummary;
928
+ /**
929
+ * E7: getDailyCostStats — 按天统计
930
+ */
931
+ getDailyCostStats(tenantId: string, days?: number): DailyCostStats[];
932
+ /**
933
+ * E9: 计算工具调用成本
934
+ */
935
+ calculateToolCost(toolName: string, tokenCount?: number): number;
936
+ /**
937
+ * E10: 计算人工审批成本
938
+ */
939
+ calculateHumanReviewCost(waitTimeMs: number, reviewTimeMs: number): HumanReviewCost;
940
+ /**
941
+ * 设置租户预算
942
+ */
943
+ setBudget(tenantId: string, budgetUsd: number): void;
944
+ /**
945
+ * 获取租户预算使用率
946
+ */
947
+ getBudgetUtilization(tenantId: string): {
948
+ used: number;
949
+ limit: number;
950
+ utilization: number;
951
+ };
952
+ private checkBudget;
953
+ private audit;
954
+ }
955
+ declare function createCostGateEnhanced(config?: Partial<CostGateEnhancedConfig>): CostGateEnhancedEngine;
956
+
957
+ /**
958
+ * server/sovr/budgetMultiLevel.ts
959
+ *
960
+ * 多层预算引擎 — 补齐 F6/F7/F8 缺口
961
+ *
962
+ * 功能:
963
+ * - F6: 多层预算(组织 → 团队 → 项目 → Agent 四级)
964
+ * - F7: 预算告警(阈值触发 + 趋势预测)
965
+ * - F8: 成本报告(多维度分析 + 导出)
966
+ *
967
+ * 设计原则:纯逻辑模块,告警通过回调注入
968
+ */
969
+ type BudgetLevel = 'organization' | 'team' | 'project' | 'agent';
970
+ interface BudgetNode {
971
+ id: string;
972
+ name: string;
973
+ level: BudgetLevel;
974
+ parentId: string | null;
975
+ budgetUsd: number;
976
+ spentUsd: number;
977
+ children: string[];
978
+ alertRules: AlertRule[];
979
+ metadata?: Record<string, unknown>;
980
+ }
981
+ interface AlertRule {
982
+ id: string;
983
+ threshold: number;
984
+ severity: 'info' | 'warning' | 'critical';
985
+ action: 'notify' | 'throttle' | 'block';
986
+ cooldownMs: number;
987
+ lastTriggeredAt?: number;
988
+ }
989
+ interface BudgetAlert {
990
+ ruleId: string;
991
+ nodeId: string;
992
+ nodeName: string;
993
+ level: BudgetLevel;
994
+ severity: AlertRule['severity'];
995
+ action: AlertRule['action'];
996
+ utilization: number;
997
+ budgetUsd: number;
998
+ spentUsd: number;
999
+ remainingUsd: number;
1000
+ predictedExhaustionDate?: string;
1001
+ timestamp: number;
1002
+ }
1003
+ interface CostReport {
1004
+ reportId: string;
1005
+ generatedAt: number;
1006
+ period: {
1007
+ start: number;
1008
+ end: number;
1009
+ };
1010
+ totalBudgetUsd: number;
1011
+ totalSpentUsd: number;
1012
+ utilization: number;
1013
+ byLevel: Record<BudgetLevel, {
1014
+ budget: number;
1015
+ spent: number;
1016
+ count: number;
1017
+ }>;
1018
+ topSpenders: {
1019
+ id: string;
1020
+ name: string;
1021
+ level: BudgetLevel;
1022
+ spent: number;
1023
+ }[];
1024
+ alerts: BudgetAlert[];
1025
+ trend: {
1026
+ date: string;
1027
+ spent: number;
1028
+ }[];
1029
+ }
1030
+ interface MultiLevelBudgetConfig {
1031
+ defaultAlertRules: AlertRule[];
1032
+ trendWindowDays: number;
1033
+ onAlert?: (alert: BudgetAlert) => void;
1034
+ onAudit?: (event: {
1035
+ type: string;
1036
+ details: Record<string, unknown>;
1037
+ timestamp: number;
1038
+ }) => void;
1039
+ }
1040
+ declare class MultiLevelBudgetEngine {
1041
+ private nodes;
1042
+ private spendHistory;
1043
+ private config;
1044
+ constructor(config?: Partial<MultiLevelBudgetConfig>);
1045
+ /**
1046
+ * F6: 创建预算节点
1047
+ */
1048
+ createNode(node: Omit<BudgetNode, 'spentUsd' | 'children' | 'alertRules'> & {
1049
+ alertRules?: AlertRule[];
1050
+ }): BudgetNode;
1051
+ /**
1052
+ * F6: 记录支出(向上冒泡到所有父级)
1053
+ */
1054
+ recordSpend(nodeId: string, amount: number): BudgetAlert[];
1055
+ /**
1056
+ * F6: 获取节点预算状态(含子节点汇总)
1057
+ */
1058
+ getNodeStatus(nodeId: string): {
1059
+ node: BudgetNode;
1060
+ utilization: number;
1061
+ childrenSpent: number;
1062
+ remaining: number;
1063
+ } | null;
1064
+ /**
1065
+ * F7: 预测预算耗尽日期
1066
+ */
1067
+ predictExhaustion(nodeId: string): string | null;
1068
+ /**
1069
+ * F8: 生成成本报告
1070
+ */
1071
+ generateReport(rootNodeId?: string): CostReport;
1072
+ /**
1073
+ * 获取所有节点
1074
+ */
1075
+ listNodes(level?: BudgetLevel): BudgetNode[];
1076
+ private checkAlerts;
1077
+ private getChildrenSpent;
1078
+ private getSubtree;
1079
+ private generateTrend;
1080
+ }
1081
+ declare function createMultiLevelBudget(config?: Partial<MultiLevelBudgetConfig>): MultiLevelBudgetEngine;
1082
+
1083
+ /**
1084
+ * server/sovr/evolutionChannel.ts
1085
+ *
1086
+ * 受控演化通道 — 补齐 B8 缺口
1087
+ *
1088
+ * 功能:
1089
+ * - 策略版本管理(版本化策略发布)
1090
+ * - 灰度发布(canary release for policies)
1091
+ * - A/B 测试策略(双策略并行评估)
1092
+ * - 回滚机制(一键回退到上一版本)
1093
+ * - 演化审计(所有策略变更记录)
1094
+ *
1095
+ * 设计原则:纯逻辑模块,无数据库依赖
1096
+ */
1097
+ interface PolicyVersion {
1098
+ id: string;
1099
+ version: string;
1100
+ name: string;
1101
+ rules: PolicyRule$1[];
1102
+ createdAt: number;
1103
+ createdBy: string;
1104
+ status: 'draft' | 'canary' | 'active' | 'deprecated' | 'rollback';
1105
+ canaryPercent: number;
1106
+ metadata?: Record<string, unknown>;
1107
+ }
1108
+ interface PolicyRule$1 {
1109
+ id: string;
1110
+ action: string;
1111
+ resource: string;
1112
+ decision: 'ALLOW' | 'DENY' | 'REVIEW';
1113
+ conditions?: Record<string, unknown>;
1114
+ priority: number;
1115
+ }
1116
+ interface EvolutionEvent {
1117
+ type: 'publish' | 'canary_start' | 'canary_promote' | 'canary_rollback' | 'deprecate' | 'ab_test_start' | 'ab_test_end';
1118
+ policyId: string;
1119
+ version: string;
1120
+ timestamp: number;
1121
+ actor: string;
1122
+ details?: Record<string, unknown>;
1123
+ }
1124
+ interface ABTestConfig {
1125
+ id: string;
1126
+ controlVersionId: string;
1127
+ treatmentVersionId: string;
1128
+ trafficSplit: number;
1129
+ startedAt: number;
1130
+ metrics: ABTestMetrics;
1131
+ status: 'running' | 'completed' | 'aborted';
1132
+ }
1133
+ interface ABTestMetrics {
1134
+ controlDecisions: number;
1135
+ treatmentDecisions: number;
1136
+ controlAllowRate: number;
1137
+ treatmentAllowRate: number;
1138
+ controlAvgLatencyMs: number;
1139
+ treatmentAvgLatencyMs: number;
1140
+ }
1141
+ interface EvolutionConfig {
1142
+ maxVersions: number;
1143
+ canaryMinDurationMs: number;
1144
+ autoPromoteThreshold: number;
1145
+ onAudit?: (event: EvolutionEvent) => void;
1146
+ }
1147
+ declare class EvolutionChannelEngine {
1148
+ private versions;
1149
+ private activeVersionId;
1150
+ private canaryVersionId;
1151
+ private abTests;
1152
+ private config;
1153
+ constructor(config?: Partial<EvolutionConfig>);
1154
+ /**
1155
+ * 发布新策略版本
1156
+ */
1157
+ publish(version: PolicyVersion): PolicyVersion;
1158
+ /**
1159
+ * 启动灰度发布
1160
+ */
1161
+ startCanary(versionId: string, percent: number, actor: string): boolean;
1162
+ /**
1163
+ * 灰度晋升为正式版本
1164
+ */
1165
+ promoteCanary(actor: string): boolean;
1166
+ /**
1167
+ * 灰度回滚
1168
+ */
1169
+ rollbackCanary(actor: string): boolean;
1170
+ /**
1171
+ * 路由决策:根据灰度百分比选择策略版本
1172
+ */
1173
+ resolveVersion(requestHash?: number): PolicyVersion | null;
1174
+ /**
1175
+ * 启动 A/B 测试
1176
+ */
1177
+ startABTest(testId: string, controlId: string, treatmentId: string, trafficSplit: number, actor: string): ABTestConfig | null;
1178
+ /**
1179
+ * A/B 测试路由
1180
+ */
1181
+ resolveABTest(testId: string, requestHash?: number): {
1182
+ version: PolicyVersion;
1183
+ group: 'control' | 'treatment';
1184
+ } | null;
1185
+ /**
1186
+ * 结束 A/B 测试
1187
+ */
1188
+ endABTest(testId: string, actor: string): ABTestConfig | null;
1189
+ /**
1190
+ * 获取所有版本
1191
+ */
1192
+ listVersions(): PolicyVersion[];
1193
+ /**
1194
+ * 获取当前 active 版本
1195
+ */
1196
+ getActiveVersion(): PolicyVersion | null;
1197
+ private cleanupOldVersions;
1198
+ private audit;
1199
+ }
1200
+ declare function createEvolutionChannel(config?: Partial<EvolutionConfig>): EvolutionChannelEngine;
1201
+
1
1202
  /**
2
1203
  * @sovr/engine — Unified Policy Engine
3
1204
  *
@@ -214,4 +1415,4 @@ declare class PolicyEngine {
214
1415
  }): void;
215
1416
  }
216
1417
 
217
- export { type AuditEvent, type Channel, DEFAULT_RULES, type EngineConfig, type EngineTier, type EngineTierLimits, type EvalRequest, type EvalResult, type ExecContext, type HttpContext, type McpContext, PolicyEngine, type PolicyRule, type RiskLevel, type RuleCondition, type SqlContext, type Verdict, PolicyEngine as default };
1418
+ export { type ABTestConfig, AdaptiveThresholdManager, type AdaptiveThresholdOptions, type AdjustmentResult, type AggregateSnapshot, type AuditEvent, AutoHardenEngine, type BudgetAlert, type BudgetLevel, type BudgetNode, type Channel, type ComparisonNode, type CompiledExpression, type ConsistencyMismatch, type ConsistencyResult, type CostAuditEvent, type CostCategory, type CostEstimate, type CostEstimateRequest, type CostGateEnhancedConfig, CostGateEnhancedEngine, type CostRecord, type CostReport, type CostSummary, DEFAULT_RULES, type DecisionFeedback, type DriftConfig, type DriftResult, type EngineConfig, type EngineTier, type EngineTierLimits, type EstimateAccuracy, type EvalContext, type EvalRequest, type EvalResult, EvolutionChannelEngine, type EvolutionConfig, type EvolutionEvent, type ExecContext, type ExprTreePolicyRule, type ExpressionNode, type FeatureSwitchDef, type FeatureSwitchState, FeatureSwitchesManager, type FeatureSwitchesOptions, type FunctionNode, type HardenConfig, type HardenEvent, type HardenLevel, type HardenMeasure, type HardenMeasureType, type HardenState, type HttpContext, type LiteralNode, type LogicalNode, type McpContext, type ModelPricing, type MultiLevelBudgetConfig, MultiLevelBudgetEngine, type NotNode, PolicyEngine, type PolicyRule, type PolicySnapshot, type PolicyVersion, type PricingEvalRequest, type PricingEvalResult, type PricingRule, PricingRulesEngine, type RecalcEngineConfig, type RecalcGranularity, type RecalcHandler, type RecalcTask, type RecalcTaskStatus, type RecalcTriggerType, RecalculationEngine, type RiskLevel, type RuleCondition, type RuleEvalResult, SOVR_FEATURE_SWITCHES, SemanticDriftDetectorEngine, type SemanticFingerprint, type SqlContext, type ThresholdConfig, type ToolPricing, type VariableNode, type Verdict, compileFromJSON, compileRuleSet, createAutoHardenEngine, createCostGateEnhanced, createEvolutionChannel, createMultiLevelBudget, createRecalculationEngine, createSemanticDriftDetector, PolicyEngine as default, estimateCost, evaluateRules, getAccuracyStats, getModelPricingTable, getToolPricingTable, recordActualCost, registerFunction, updateModelPricing, updateToolPricing };