@sovr/engine 3.3.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.js CHANGED
@@ -21,16 +21,35 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  AdaptiveThresholdManager: () => AdaptiveThresholdManager,
24
+ AutoHardenEngine: () => AutoHardenEngine,
25
+ CostGateEnhancedEngine: () => CostGateEnhancedEngine,
24
26
  DEFAULT_RULES: () => DEFAULT_RULES,
27
+ EvolutionChannelEngine: () => EvolutionChannelEngine,
25
28
  FeatureSwitchesManager: () => FeatureSwitchesManager,
29
+ MultiLevelBudgetEngine: () => MultiLevelBudgetEngine,
26
30
  PolicyEngine: () => PolicyEngine,
27
31
  PricingRulesEngine: () => PricingRulesEngine,
32
+ RecalculationEngine: () => RecalculationEngine,
28
33
  SOVR_FEATURE_SWITCHES: () => SOVR_FEATURE_SWITCHES,
34
+ SemanticDriftDetectorEngine: () => SemanticDriftDetectorEngine,
29
35
  compileFromJSON: () => compileFromJSON,
30
36
  compileRuleSet: () => compileRuleSet,
37
+ createAutoHardenEngine: () => createAutoHardenEngine,
38
+ createCostGateEnhanced: () => createCostGateEnhanced,
39
+ createEvolutionChannel: () => createEvolutionChannel,
40
+ createMultiLevelBudget: () => createMultiLevelBudget,
41
+ createRecalculationEngine: () => createRecalculationEngine,
42
+ createSemanticDriftDetector: () => createSemanticDriftDetector,
31
43
  default: () => index_default,
44
+ estimateCost: () => estimateCost,
32
45
  evaluateRules: () => evaluateRules,
33
- registerFunction: () => registerFunction
46
+ getAccuracyStats: () => getAccuracyStats,
47
+ getModelPricingTable: () => getModelPricingTable,
48
+ getToolPricingTable: () => getToolPricingTable,
49
+ recordActualCost: () => recordActualCost,
50
+ registerFunction: () => registerFunction,
51
+ updateModelPricing: () => updateModelPricing,
52
+ updateToolPricing: () => updateToolPricing
34
53
  });
35
54
  module.exports = __toCommonJS(index_exports);
36
55
 
@@ -685,6 +704,1356 @@ var PricingRulesEngine = class {
685
704
  }
686
705
  };
687
706
 
707
+ // src/recalculationEngine.ts
708
+ var idCounter = 0;
709
+ function genId(prefix) {
710
+ return `${prefix}_${Date.now()}_${++idCounter}`;
711
+ }
712
+ function simpleHash(data) {
713
+ let hash = 0;
714
+ for (let i = 0; i < data.length; i++) {
715
+ const char = data.charCodeAt(i);
716
+ hash = (hash << 5) - hash + char;
717
+ hash = hash & hash;
718
+ }
719
+ return "h_" + Math.abs(hash).toString(16).padStart(8, "0");
720
+ }
721
+ var RecalculationEngine = class {
722
+ tasks = /* @__PURE__ */ new Map();
723
+ consistencyResults = /* @__PURE__ */ new Map();
724
+ snapshots = /* @__PURE__ */ new Map();
725
+ handlers = /* @__PURE__ */ new Map();
726
+ config;
727
+ constructor(config = {}) {
728
+ this.config = { maxRangeDays: 30, ...config };
729
+ }
730
+ /** G3: Trigger recalculation */
731
+ triggerRecalculation(input) {
732
+ if (input.fromTs >= input.toTs) throw new Error("fromTs must be before toTs");
733
+ const maxMs = this.config.maxRangeDays * 864e5;
734
+ if (input.toTs - input.fromTs > maxMs) throw new Error(`Range exceeds ${this.config.maxRangeDays} days`);
735
+ const task = {
736
+ id: genId("recalc"),
737
+ tenantId: input.tenantId,
738
+ triggerType: input.triggerType,
739
+ triggeredBy: input.triggeredBy,
740
+ reason: input.reason,
741
+ fromTs: input.fromTs,
742
+ toTs: input.toTs,
743
+ granularity: input.granularity || "all",
744
+ incremental: input.incremental || false,
745
+ incrementalCheckpoint: input.incrementalCheckpoint,
746
+ status: "pending",
747
+ progress: 0,
748
+ bucketsProcessed: 0,
749
+ rowsUpserted: 0,
750
+ createdAt: Date.now(),
751
+ traceId: genId("trace")
752
+ };
753
+ this.tasks.set(task.id, task);
754
+ this.audit("recalc.triggered", { taskId: task.id, triggerType: task.triggerType, reason: task.reason });
755
+ return task;
756
+ }
757
+ /** Execute recalculation task */
758
+ async executeTask(taskId) {
759
+ const task = this.tasks.get(taskId);
760
+ if (!task) throw new Error(`Task not found: ${taskId}`);
761
+ if (task.status !== "pending") throw new Error(`Task not pending: ${task.status}`);
762
+ task.status = "running";
763
+ task.startedAt = Date.now();
764
+ this.audit("recalc.started", { taskId: task.id });
765
+ try {
766
+ const preSnapshot = this.createSnapshot(task.tenantId, "pre_recalc", task.id);
767
+ const handler = this.handlers.get(task.granularity);
768
+ if (handler) {
769
+ const result = await handler(task);
770
+ task.bucketsProcessed = result.bucketsProcessed;
771
+ task.rowsUpserted = result.rowsUpserted;
772
+ const postSnapshot = this.createSnapshot(task.tenantId, "post_recalc", task.id, result.metrics);
773
+ task.consistencyResult = this.verifyConsistency(task.id, preSnapshot, postSnapshot, result.metrics);
774
+ } else {
775
+ const segmentMs = task.granularity === "5m" ? 3e5 : task.granularity === "1h" ? 36e5 : task.granularity === "1d" ? 864e5 : 36e5;
776
+ const totalSegments = Math.ceil((task.toTs - task.fromTs) / segmentMs);
777
+ task.bucketsProcessed = totalSegments;
778
+ task.progress = 100;
779
+ }
780
+ task.status = "completed";
781
+ task.completedAt = Date.now();
782
+ task.progress = 100;
783
+ this.audit("recalc.completed", {
784
+ taskId: task.id,
785
+ bucketsProcessed: task.bucketsProcessed,
786
+ durationMs: task.completedAt - (task.startedAt || 0),
787
+ consistencyRate: task.consistencyResult?.consistencyRate
788
+ });
789
+ return task;
790
+ } catch (error) {
791
+ task.status = "failed";
792
+ task.error = error instanceof Error ? error.message : "Unknown error";
793
+ task.completedAt = Date.now();
794
+ this.audit("recalc.failed", { taskId: task.id, error: task.error });
795
+ return task;
796
+ }
797
+ }
798
+ /** G4: Verify consistency */
799
+ verifyConsistency(taskId, preSnapshot, postSnapshot, recalculatedMetrics) {
800
+ const mismatches = [];
801
+ const metrics = recalculatedMetrics || postSnapshot.metrics;
802
+ let totalComparisons = 0;
803
+ let matchCount = 0;
804
+ for (const [metric, recalcValue] of Object.entries(metrics)) {
805
+ const currentValue = preSnapshot.metrics[metric];
806
+ if (currentValue === void 0) continue;
807
+ totalComparisons++;
808
+ const deviation = Math.abs(recalcValue - currentValue);
809
+ const deviationPercent = currentValue !== 0 ? deviation / Math.abs(currentValue) * 100 : recalcValue !== 0 ? 100 : 0;
810
+ if (deviationPercent < 0.01) {
811
+ matchCount++;
812
+ } else {
813
+ mismatches.push({
814
+ metric,
815
+ bucket: `${preSnapshot.id} \u2192 ${postSnapshot.id}`,
816
+ currentValue,
817
+ recalculatedValue: recalcValue,
818
+ deviation,
819
+ deviationPercent: Math.round(deviationPercent * 100) / 100,
820
+ severity: deviationPercent > 10 ? "critical" : deviationPercent > 5 ? "high" : deviationPercent > 1 ? "medium" : "low"
821
+ });
822
+ }
823
+ }
824
+ const consistencyRate = totalComparisons > 0 ? Math.round(matchCount / totalComparisons * 1e4) / 100 : 100;
825
+ const verificationHash = simpleHash(JSON.stringify({ taskId, pre: preSnapshot.hash, post: postSnapshot.hash, mismatches }));
826
+ const result = {
827
+ id: genId("cr"),
828
+ taskId,
829
+ status: mismatches.length === 0 ? "consistent" : consistencyRate > 95 ? "partial" : "inconsistent",
830
+ totalComparisons,
831
+ matchCount,
832
+ mismatchCount: mismatches.length,
833
+ consistencyRate,
834
+ mismatches,
835
+ verifiedAt: Date.now(),
836
+ verificationHash
837
+ };
838
+ this.consistencyResults.set(result.id, result);
839
+ this.audit("recalc.consistency_check", { taskId, consistencyRate, mismatchCount: mismatches.length, status: result.status });
840
+ return result;
841
+ }
842
+ /** G5: Incremental recalculation */
843
+ triggerIncremental(input) {
844
+ const completed = Array.from(this.tasks.values()).filter((t) => t.tenantId === input.tenantId && t.status === "completed").sort((a, b) => (b.completedAt || 0) - (a.completedAt || 0));
845
+ const last = completed[0];
846
+ const fromTs = last ? last.toTs : Date.now() - 864e5;
847
+ return this.triggerRecalculation({
848
+ tenantId: input.tenantId,
849
+ triggerType: "manual",
850
+ triggeredBy: input.triggeredBy,
851
+ reason: input.reason,
852
+ fromTs,
853
+ toTs: Date.now(),
854
+ granularity: input.granularity,
855
+ incremental: true,
856
+ incrementalCheckpoint: last?.id
857
+ });
858
+ }
859
+ /** Create aggregate snapshot */
860
+ createSnapshot(tenantId, snapshotType, taskId, metrics) {
861
+ const m = metrics || {};
862
+ const snapshot = {
863
+ id: genId("snap"),
864
+ tenantId,
865
+ snapshotType,
866
+ taskId,
867
+ metrics: m,
868
+ hash: simpleHash(JSON.stringify(m)),
869
+ createdAt: Date.now()
870
+ };
871
+ this.snapshots.set(snapshot.id, snapshot);
872
+ return snapshot;
873
+ }
874
+ /** Register recalculation handler */
875
+ registerHandler(granularity, handler) {
876
+ this.handlers.set(granularity, handler);
877
+ }
878
+ /** Query functions */
879
+ getTask(taskId) {
880
+ return this.tasks.get(taskId);
881
+ }
882
+ getTasks(tenantId, limit = 20) {
883
+ return Array.from(this.tasks.values()).filter((t) => t.tenantId === tenantId).sort((a, b) => b.createdAt - a.createdAt).slice(0, limit);
884
+ }
885
+ getConsistencyResult(taskId) {
886
+ return Array.from(this.consistencyResults.values()).find((r) => r.taskId === taskId);
887
+ }
888
+ getSnapshot(snapshotId) {
889
+ return this.snapshots.get(snapshotId);
890
+ }
891
+ cancelTask(taskId) {
892
+ const task = this.tasks.get(taskId);
893
+ if (!task || task.status !== "pending") return false;
894
+ task.status = "cancelled";
895
+ return true;
896
+ }
897
+ audit(type, details) {
898
+ if (this.config.onAudit) {
899
+ this.config.onAudit({ type, details, timestamp: Date.now() });
900
+ }
901
+ }
902
+ };
903
+ function createRecalculationEngine(config) {
904
+ return new RecalculationEngine(config);
905
+ }
906
+
907
+ // src/autoHarden.ts
908
+ var LEVEL_PRIORITY = {
909
+ normal: 0,
910
+ elevated: 1,
911
+ hardened: 2,
912
+ lockdown: 3
913
+ };
914
+ var DEFAULT_CONFIG = {
915
+ enabled: true,
916
+ levelMeasures: {
917
+ normal: [],
918
+ elevated: ["enhanced_audit", "alert_admin"],
919
+ hardened: ["gate_level_upgrade", "rate_limit_reduce", "enhanced_audit", "alert_admin"],
920
+ lockdown: ["gate_level_upgrade", "rate_limit_reduce", "enhanced_audit", "ip_block", "session_invalidate", "feature_disable", "alert_admin"]
921
+ },
922
+ autoRollbackMs: 30 * 60 * 1e3,
923
+ rateLimitReductionFactor: 0.25,
924
+ notifyAdmin: true
925
+ };
926
+ var idCounter2 = 0;
927
+ function genId2(prefix) {
928
+ return `${prefix}_${Date.now()}_${++idCounter2}`;
929
+ }
930
+ var AutoHardenEngine = class {
931
+ states = /* @__PURE__ */ new Map();
932
+ history = [];
933
+ config;
934
+ rollbackTimers = /* @__PURE__ */ new Map();
935
+ maxHistory = 1e3;
936
+ constructor(config = {}) {
937
+ this.config = { ...DEFAULT_CONFIG, ...config };
938
+ }
939
+ /** Get tenant harden state */
940
+ getState(tenantId) {
941
+ return this.states.get(tenantId) || { currentLevel: "normal", activeMeasures: [] };
942
+ }
943
+ /** Get current harden level */
944
+ getLevel(tenantId) {
945
+ return this.getState(tenantId).currentLevel;
946
+ }
947
+ /** Auto-harden (main entry) */
948
+ async harden(input) {
949
+ if (!this.config.enabled) throw new Error("AutoHarden is disabled");
950
+ const state = this.getState(input.tenantId);
951
+ const traceId = genId2("trace");
952
+ const targetLevel = input.targetLevel || this.determineLevel(
953
+ input.manipulationScore || 0,
954
+ input.reasonCodes || []
955
+ );
956
+ if (LEVEL_PRIORITY[targetLevel] <= LEVEL_PRIORITY[state.currentLevel]) {
957
+ const event2 = {
958
+ id: genId2("harden"),
959
+ tenantId: input.tenantId,
960
+ triggeredBy: input.triggeredBy,
961
+ reason: `Already at ${state.currentLevel}, target ${targetLevel} skipped`,
962
+ previousLevel: state.currentLevel,
963
+ newLevel: state.currentLevel,
964
+ measures: [],
965
+ createdAt: Date.now(),
966
+ rolledBack: false,
967
+ traceId
968
+ };
969
+ this.history.push(event2);
970
+ return event2;
971
+ }
972
+ const measures = this.applyMeasures(input.tenantId, targetLevel);
973
+ const previousLevel = state.currentLevel;
974
+ state.currentLevel = targetLevel;
975
+ state.activeMeasures = measures;
976
+ state.hardenedSince = Date.now();
977
+ if (this.config.autoRollbackMs > 0) {
978
+ state.expectedRollbackAt = Date.now() + this.config.autoRollbackMs;
979
+ this.scheduleAutoRollback(input.tenantId, this.config.autoRollbackMs);
980
+ }
981
+ this.states.set(input.tenantId, state);
982
+ const event = {
983
+ id: genId2("harden"),
984
+ tenantId: input.tenantId,
985
+ triggeredBy: input.triggeredBy,
986
+ reason: input.reason,
987
+ previousLevel,
988
+ newLevel: targetLevel,
989
+ measures,
990
+ createdAt: Date.now(),
991
+ rolledBack: false,
992
+ traceId
993
+ };
994
+ this.history.push(event);
995
+ if (this.history.length > this.maxHistory) this.history.shift();
996
+ state.lastEvent = event;
997
+ this.audit(event.rolledBack ? "HARDEN_ROLLBACK" : "HARDEN_ACTIVATED", {
998
+ tenantId: event.tenantId,
999
+ previousLevel,
1000
+ newLevel: targetLevel,
1001
+ measuresCount: measures.length,
1002
+ measures: measures.map((m) => m.type)
1003
+ });
1004
+ if (this.config.notifyAdmin && this.config.onNotifyAdmin) {
1005
+ try {
1006
+ await this.config.onNotifyAdmin(event);
1007
+ } catch {
1008
+ }
1009
+ }
1010
+ return event;
1011
+ }
1012
+ /** Manual rollback */
1013
+ async rollback(tenantId, rolledBackBy, reason) {
1014
+ const state = this.getState(tenantId);
1015
+ if (state.currentLevel === "normal") throw new Error("Already at normal level");
1016
+ const timer = this.rollbackTimers.get(tenantId);
1017
+ if (timer) {
1018
+ clearTimeout(timer);
1019
+ this.rollbackTimers.delete(tenantId);
1020
+ }
1021
+ const previousLevel = state.currentLevel;
1022
+ const event = {
1023
+ id: genId2("harden"),
1024
+ tenantId,
1025
+ triggeredBy: rolledBackBy,
1026
+ reason: reason || `Manual rollback from ${previousLevel}`,
1027
+ previousLevel,
1028
+ newLevel: "normal",
1029
+ measures: state.activeMeasures.map((m) => ({ ...m, rolledBackAt: Date.now() })),
1030
+ createdAt: Date.now(),
1031
+ rolledBack: true,
1032
+ rolledBackAt: Date.now(),
1033
+ traceId: genId2("trace")
1034
+ };
1035
+ state.currentLevel = "normal";
1036
+ state.activeMeasures = [];
1037
+ state.hardenedSince = void 0;
1038
+ state.expectedRollbackAt = void 0;
1039
+ state.lastEvent = event;
1040
+ this.states.set(tenantId, state);
1041
+ this.history.push(event);
1042
+ this.audit("HARDEN_ROLLBACK", { tenantId, previousLevel, rolledBackBy });
1043
+ return event;
1044
+ }
1045
+ /** Update config */
1046
+ updateConfig(config) {
1047
+ this.config = { ...this.config, ...config };
1048
+ return this.config;
1049
+ }
1050
+ /** Get config */
1051
+ getConfig() {
1052
+ return { ...this.config };
1053
+ }
1054
+ /** Get history */
1055
+ getHistory(tenantId, limit = 50) {
1056
+ const filtered = tenantId ? this.history.filter((e) => e.tenantId === tenantId) : this.history;
1057
+ return filtered.slice(-limit);
1058
+ }
1059
+ /** Get all active hardened states */
1060
+ getActiveStates() {
1061
+ const result = [];
1062
+ this.states.forEach((state, tenantId) => {
1063
+ if (state.currentLevel !== "normal") result.push({ tenantId, state });
1064
+ });
1065
+ return result;
1066
+ }
1067
+ /** Cleanup timers */
1068
+ destroy() {
1069
+ this.rollbackTimers.forEach((t) => clearTimeout(t));
1070
+ this.rollbackTimers.clear();
1071
+ }
1072
+ // Internal
1073
+ determineLevel(score, reasonCodes) {
1074
+ if (reasonCodes.some((c) => c.startsWith("CRIT_"))) return "lockdown";
1075
+ if (score >= 0.8) return "lockdown";
1076
+ if (score >= 0.5) return "hardened";
1077
+ if (score >= 0.3) return "elevated";
1078
+ return "normal";
1079
+ }
1080
+ applyMeasures(tenantId, level) {
1081
+ const types = this.config.levelMeasures[level];
1082
+ return types.map((type) => ({
1083
+ id: genId2("measure"),
1084
+ type,
1085
+ description: this.getMeasureDescription(type, level),
1086
+ applied: true,
1087
+ appliedAt: Date.now()
1088
+ }));
1089
+ }
1090
+ getMeasureDescription(type, level) {
1091
+ const d = {
1092
+ gate_level_upgrade: `Gate approval level upgraded to ${level}`,
1093
+ rate_limit_reduce: `Rate limit reduced to ${this.config.rateLimitReductionFactor * 100}%`,
1094
+ enhanced_audit: "Enhanced audit mode enabled (full recording)",
1095
+ ip_block: "Suspicious IPs blocked",
1096
+ session_invalidate: "All active sessions invalidated",
1097
+ feature_disable: "Non-essential features disabled",
1098
+ alert_admin: "Admin security alert sent"
1099
+ };
1100
+ return d[type] || type;
1101
+ }
1102
+ scheduleAutoRollback(tenantId, delayMs) {
1103
+ const existing = this.rollbackTimers.get(tenantId);
1104
+ if (existing) clearTimeout(existing);
1105
+ const timer = setTimeout(async () => {
1106
+ try {
1107
+ await this.rollback(tenantId, "system:auto_rollback", "Auto rollback after timeout");
1108
+ } catch {
1109
+ }
1110
+ this.rollbackTimers.delete(tenantId);
1111
+ }, delayMs);
1112
+ this.rollbackTimers.set(tenantId, timer);
1113
+ }
1114
+ audit(type, details) {
1115
+ if (this.config.onAudit) {
1116
+ this.config.onAudit({ type, details, timestamp: Date.now() });
1117
+ }
1118
+ }
1119
+ };
1120
+ function createAutoHardenEngine(config) {
1121
+ return new AutoHardenEngine(config);
1122
+ }
1123
+
1124
+ // src/costEstimator.ts
1125
+ var DEFAULT_MODEL_PRICING = [
1126
+ {
1127
+ modelId: "gpt-4o",
1128
+ modelName: "GPT-4o",
1129
+ inputPricePerKToken: 25e-4,
1130
+ outputPricePerKToken: 0.01,
1131
+ cachedInputPricePerKToken: 125e-5,
1132
+ maxContextLength: 128e3,
1133
+ updatedAt: /* @__PURE__ */ new Date("2025-01-01")
1134
+ },
1135
+ {
1136
+ modelId: "gpt-4o-mini",
1137
+ modelName: "GPT-4o Mini",
1138
+ inputPricePerKToken: 15e-5,
1139
+ outputPricePerKToken: 6e-4,
1140
+ cachedInputPricePerKToken: 75e-6,
1141
+ maxContextLength: 128e3,
1142
+ updatedAt: /* @__PURE__ */ new Date("2025-01-01")
1143
+ },
1144
+ {
1145
+ modelId: "claude-3.5-sonnet",
1146
+ modelName: "Claude 3.5 Sonnet",
1147
+ inputPricePerKToken: 3e-3,
1148
+ outputPricePerKToken: 0.015,
1149
+ cachedInputPricePerKToken: 3e-4,
1150
+ maxContextLength: 2e5,
1151
+ updatedAt: /* @__PURE__ */ new Date("2025-01-01")
1152
+ },
1153
+ {
1154
+ modelId: "claude-3.5-haiku",
1155
+ modelName: "Claude 3.5 Haiku",
1156
+ inputPricePerKToken: 8e-4,
1157
+ outputPricePerKToken: 4e-3,
1158
+ cachedInputPricePerKToken: 8e-5,
1159
+ maxContextLength: 2e5,
1160
+ updatedAt: /* @__PURE__ */ new Date("2025-01-01")
1161
+ },
1162
+ {
1163
+ modelId: "gemini-2.0-flash",
1164
+ modelName: "Gemini 2.0 Flash",
1165
+ inputPricePerKToken: 1e-4,
1166
+ outputPricePerKToken: 4e-4,
1167
+ maxContextLength: 1e6,
1168
+ updatedAt: /* @__PURE__ */ new Date("2025-01-01")
1169
+ }
1170
+ ];
1171
+ var DEFAULT_TOOL_PRICING = [
1172
+ { toolId: "web_search", toolName: "Web Search", costPerCall: 5e-3, multiplier: 1, updatedAt: /* @__PURE__ */ new Date() },
1173
+ { toolId: "code_exec", toolName: "Code Execution", costPerCall: 2e-3, multiplier: 1, updatedAt: /* @__PURE__ */ new Date() },
1174
+ { toolId: "file_read", toolName: "File Read", costPerCall: 1e-3, multiplier: 1, updatedAt: /* @__PURE__ */ new Date() },
1175
+ { toolId: "db_query", toolName: "Database Query", costPerCall: 3e-3, multiplier: 1, updatedAt: /* @__PURE__ */ new Date() },
1176
+ { toolId: "api_call", toolName: "External API Call", costPerCall: 0.01, multiplier: 1.5, updatedAt: /* @__PURE__ */ new Date() }
1177
+ ];
1178
+ var DEFAULT_HUMAN_RATES = [
1179
+ { level: "standard", hourlyRate: 50, avgReviewMinutes: 5 },
1180
+ { level: "senior", hourlyRate: 100, avgReviewMinutes: 10 },
1181
+ { level: "executive", hourlyRate: 200, avgReviewMinutes: 15 }
1182
+ ];
1183
+ var modelPricing = [...DEFAULT_MODEL_PRICING];
1184
+ var toolPricing = [...DEFAULT_TOOL_PRICING];
1185
+ var humanRates = [...DEFAULT_HUMAN_RATES];
1186
+ var accuracyRecords = [];
1187
+ var MAX_ACCURACY_RECORDS = 1e4;
1188
+ function estimateCost(request) {
1189
+ const id = `est_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1190
+ const model = modelPricing.find((m) => m.modelId === request.modelId) || modelPricing[0];
1191
+ const inputCost = request.estimatedInputTokens / 1e3 * model.inputPricePerKToken;
1192
+ const outputCost = request.estimatedOutputTokens / 1e3 * model.outputPricePerKToken;
1193
+ const modelCostTotal = inputCost + outputCost;
1194
+ const toolItems = [];
1195
+ let toolCostTotal = 0;
1196
+ if (request.toolCalls) {
1197
+ for (const tc of request.toolCalls) {
1198
+ const tool = toolPricing.find((t) => t.toolId === tc.toolId);
1199
+ if (tool) {
1200
+ const total = tc.estimatedCalls * tool.costPerCall * tool.multiplier;
1201
+ toolItems.push({
1202
+ toolId: tc.toolId,
1203
+ calls: tc.estimatedCalls,
1204
+ costPerCall: tool.costPerCall,
1205
+ total
1206
+ });
1207
+ toolCostTotal += total;
1208
+ }
1209
+ }
1210
+ }
1211
+ let humanCost = null;
1212
+ if (request.requiresHumanReview) {
1213
+ const rate = humanRates.find((r) => r.level === (request.humanReviewLevel || "standard")) || humanRates[0];
1214
+ const humanTotal = rate.avgReviewMinutes / 60 * rate.hourlyRate;
1215
+ humanCost = {
1216
+ level: rate.level,
1217
+ hourlyRate: rate.hourlyRate,
1218
+ estimatedMinutes: rate.avgReviewMinutes,
1219
+ total: humanTotal
1220
+ };
1221
+ }
1222
+ const totalCost = modelCostTotal + toolCostTotal + (humanCost?.total || 0);
1223
+ const avgDeviation = getAverageDeviation();
1224
+ const confidence = {
1225
+ low: totalCost * (1 - avgDeviation),
1226
+ high: totalCost * (1 + avgDeviation),
1227
+ level: Math.max(0, 1 - avgDeviation)
1228
+ };
1229
+ return {
1230
+ id,
1231
+ modelCost: {
1232
+ inputCost: Math.round(inputCost * 1e6) / 1e6,
1233
+ outputCost: Math.round(outputCost * 1e6) / 1e6,
1234
+ total: Math.round(modelCostTotal * 1e6) / 1e6
1235
+ },
1236
+ toolCost: {
1237
+ items: toolItems,
1238
+ total: Math.round(toolCostTotal * 1e6) / 1e6
1239
+ },
1240
+ humanCost,
1241
+ totalCost: Math.round(totalCost * 1e6) / 1e6,
1242
+ confidence,
1243
+ estimatedAt: /* @__PURE__ */ new Date()
1244
+ };
1245
+ }
1246
+ function recordActualCost(estimateId, actualCost) {
1247
+ const record = {
1248
+ estimateId,
1249
+ estimatedCost: 0,
1250
+ // 需要外部传入
1251
+ actualCost,
1252
+ deviation: 0,
1253
+ deviationPercent: 0,
1254
+ recordedAt: /* @__PURE__ */ new Date()
1255
+ };
1256
+ accuracyRecords.push(record);
1257
+ if (accuracyRecords.length > MAX_ACCURACY_RECORDS) accuracyRecords.shift();
1258
+ return record;
1259
+ }
1260
+ function getAverageDeviation() {
1261
+ if (accuracyRecords.length === 0) return 0.3;
1262
+ const deviations = accuracyRecords.filter((r) => r.estimatedCost > 0).map((r) => Math.abs(r.deviationPercent));
1263
+ if (deviations.length === 0) return 0.3;
1264
+ return deviations.reduce((sum, d) => sum + d, 0) / deviations.length / 100;
1265
+ }
1266
+ function updateModelPricing(pricing) {
1267
+ const index = modelPricing.findIndex((m) => m.modelId === pricing.modelId);
1268
+ if (index >= 0) {
1269
+ modelPricing[index] = pricing;
1270
+ } else {
1271
+ modelPricing.push(pricing);
1272
+ }
1273
+ }
1274
+ function updateToolPricing(pricing) {
1275
+ const index = toolPricing.findIndex((t) => t.toolId === pricing.toolId);
1276
+ if (index >= 0) {
1277
+ toolPricing[index] = pricing;
1278
+ } else {
1279
+ toolPricing.push(pricing);
1280
+ }
1281
+ }
1282
+ function getModelPricingTable() {
1283
+ return [...modelPricing];
1284
+ }
1285
+ function getToolPricingTable() {
1286
+ return [...toolPricing];
1287
+ }
1288
+ function getAccuracyStats() {
1289
+ const avgDev = getAverageDeviation();
1290
+ return {
1291
+ totalRecords: accuracyRecords.length,
1292
+ avgDeviation: avgDev,
1293
+ avgDeviationPercent: avgDev * 100,
1294
+ confidenceLevel: Math.max(0, 1 - avgDev)
1295
+ };
1296
+ }
1297
+
1298
+ // src/semanticDriftDetector.ts
1299
+ var DEFAULT_CONFIG2 = {
1300
+ lowThreshold: 0.1,
1301
+ mediumThreshold: 0.3,
1302
+ highThreshold: 0.5,
1303
+ criticalThreshold: 0.7,
1304
+ onDriftDetected: void 0,
1305
+ onAudit: void 0
1306
+ };
1307
+ var SemanticDriftDetectorEngine = class {
1308
+ fingerprints = /* @__PURE__ */ new Map();
1309
+ history = [];
1310
+ config;
1311
+ constructor(config = {}) {
1312
+ this.config = { ...DEFAULT_CONFIG2, ...config };
1313
+ }
1314
+ /**
1315
+ * 计算策略语义指纹
1316
+ */
1317
+ computeFingerprint(snapshot) {
1318
+ const rules = snapshot.rules;
1319
+ const resourceSet = [...new Set(rules.map((r) => r.resource))].sort();
1320
+ const actionSet = [...new Set(rules.map((r) => r.action))].sort();
1321
+ const fingerprint = {
1322
+ version: snapshot.version,
1323
+ hash: this.hashRules(rules),
1324
+ ruleCount: rules.length,
1325
+ allowCount: rules.filter((r) => r.decision === "ALLOW").length,
1326
+ denyCount: rules.filter((r) => r.decision === "DENY").length,
1327
+ reviewCount: rules.filter((r) => r.decision === "REVIEW").length,
1328
+ resourceSet,
1329
+ actionSet,
1330
+ conditionDepth: this.maxConditionDepth(rules),
1331
+ timestamp: Date.now()
1332
+ };
1333
+ this.fingerprints.set(snapshot.version, fingerprint);
1334
+ return fingerprint;
1335
+ }
1336
+ /**
1337
+ * 检测两个版本间的语义漂移
1338
+ */
1339
+ detectDrift(from, to) {
1340
+ const fromRuleMap = new Map(from.rules.map((r) => [r.id, r]));
1341
+ const toRuleMap = new Map(to.rules.map((r) => [r.id, r]));
1342
+ const addedRules = [];
1343
+ const removedRules = [];
1344
+ const modifiedRules = [];
1345
+ const decisionChanges = [];
1346
+ for (const [id, toRule] of toRuleMap) {
1347
+ const fromRule = fromRuleMap.get(id);
1348
+ if (!fromRule) {
1349
+ addedRules.push(id);
1350
+ } else if (this.ruleChanged(fromRule, toRule)) {
1351
+ modifiedRules.push(id);
1352
+ if (fromRule.decision !== toRule.decision) {
1353
+ decisionChanges.push({ ruleId: id, from: fromRule.decision, to: toRule.decision });
1354
+ }
1355
+ }
1356
+ }
1357
+ for (const id of fromRuleMap.keys()) {
1358
+ if (!toRuleMap.has(id)) {
1359
+ removedRules.push(id);
1360
+ }
1361
+ }
1362
+ const fromResources = new Set(from.rules.map((r) => r.resource));
1363
+ const toResources = new Set(to.rules.map((r) => r.resource));
1364
+ const newResources = [...toResources].filter((r) => !fromResources.has(r));
1365
+ const removedResources = [...fromResources].filter((r) => !toResources.has(r));
1366
+ const totalRules = Math.max(from.rules.length, to.rules.length, 1);
1367
+ const changeCount = addedRules.length + removedRules.length + modifiedRules.length;
1368
+ const decisionWeight = decisionChanges.length * 2;
1369
+ const driftScore = Math.min(1, (changeCount + decisionWeight) / totalRules);
1370
+ let severity = "none";
1371
+ if (driftScore >= this.config.criticalThreshold) severity = "critical";
1372
+ else if (driftScore >= this.config.highThreshold) severity = "high";
1373
+ else if (driftScore >= this.config.mediumThreshold) severity = "medium";
1374
+ else if (driftScore >= this.config.lowThreshold) severity = "low";
1375
+ const result = {
1376
+ fromVersion: from.version,
1377
+ toVersion: to.version,
1378
+ driftScore,
1379
+ ruleCountDelta: to.rules.length - from.rules.length,
1380
+ addedRules,
1381
+ removedRules,
1382
+ modifiedRules,
1383
+ decisionChanges,
1384
+ newResources,
1385
+ removedResources,
1386
+ severity,
1387
+ timestamp: Date.now()
1388
+ };
1389
+ this.history.push(result);
1390
+ if (severity !== "none" && this.config.onDriftDetected) {
1391
+ this.config.onDriftDetected(result);
1392
+ }
1393
+ if (this.config.onAudit) {
1394
+ this.config.onAudit({
1395
+ type: "drift_detected",
1396
+ details: { fromVersion: from.version, toVersion: to.version, driftScore, severity },
1397
+ timestamp: Date.now()
1398
+ });
1399
+ }
1400
+ return result;
1401
+ }
1402
+ /**
1403
+ * 获取漂移历史
1404
+ */
1405
+ getDriftHistory() {
1406
+ return [...this.history];
1407
+ }
1408
+ /**
1409
+ * 获取指纹
1410
+ */
1411
+ getFingerprint(version) {
1412
+ return this.fingerprints.get(version) ?? null;
1413
+ }
1414
+ /**
1415
+ * 获取漂移趋势
1416
+ */
1417
+ getDriftTrend() {
1418
+ return this.history.map((h) => ({
1419
+ version: h.toVersion,
1420
+ driftScore: h.driftScore,
1421
+ timestamp: h.timestamp
1422
+ }));
1423
+ }
1424
+ // ============================================
1425
+ // 私有方法
1426
+ // ============================================
1427
+ hashRules(rules) {
1428
+ const sorted = [...rules].sort((a, b) => a.id.localeCompare(b.id));
1429
+ const str = sorted.map((r) => `${r.id}:${r.action}:${r.resource}:${r.decision}:${r.priority}`).join("|");
1430
+ let hash = 0;
1431
+ for (let i = 0; i < str.length; i++) {
1432
+ const char = str.charCodeAt(i);
1433
+ hash = (hash << 5) - hash + char;
1434
+ hash = hash & hash;
1435
+ }
1436
+ return "fp_" + Math.abs(hash).toString(16).padStart(8, "0");
1437
+ }
1438
+ ruleChanged(a, b) {
1439
+ return a.action !== b.action || a.resource !== b.resource || a.decision !== b.decision || a.priority !== b.priority || JSON.stringify(a.conditions) !== JSON.stringify(b.conditions);
1440
+ }
1441
+ maxConditionDepth(rules) {
1442
+ let max = 0;
1443
+ for (const r of rules) {
1444
+ if (r.conditions) {
1445
+ max = Math.max(max, this.objectDepth(r.conditions));
1446
+ }
1447
+ }
1448
+ return max;
1449
+ }
1450
+ objectDepth(obj, depth = 0) {
1451
+ let max = depth;
1452
+ for (const val of Object.values(obj)) {
1453
+ if (val && typeof val === "object" && !Array.isArray(val)) {
1454
+ max = Math.max(max, this.objectDepth(val, depth + 1));
1455
+ }
1456
+ }
1457
+ return max;
1458
+ }
1459
+ };
1460
+ function createSemanticDriftDetector(config) {
1461
+ return new SemanticDriftDetectorEngine(config);
1462
+ }
1463
+
1464
+ // src/costGateEnhanced.ts
1465
+ var DEFAULT_CONFIG3 = {
1466
+ defaultBudgetUsd: 100,
1467
+ warningThreshold: 0.8,
1468
+ criticalThreshold: 0.95,
1469
+ humanReviewHourlyRateUsd: 50,
1470
+ toolCosts: [],
1471
+ onAudit: void 0,
1472
+ onBudgetExceeded: void 0
1473
+ };
1474
+ var CostGateEnhancedEngine = class {
1475
+ records = [];
1476
+ budgets = /* @__PURE__ */ new Map();
1477
+ // tenantId → budgetUsd
1478
+ config;
1479
+ toolCostMap = /* @__PURE__ */ new Map();
1480
+ constructor(config = {}) {
1481
+ this.config = { ...DEFAULT_CONFIG3, ...config };
1482
+ for (const tc of this.config.toolCosts) {
1483
+ this.toolCostMap.set(tc.toolName, tc);
1484
+ }
1485
+ }
1486
+ /**
1487
+ * E2: 记录成本并生成汇总
1488
+ */
1489
+ recordCost(record) {
1490
+ this.records.push(record);
1491
+ this.audit("cost_recorded", record.tenantId, { record });
1492
+ return this.checkBudget(record.tenantId, record.agentId, record.action);
1493
+ }
1494
+ /**
1495
+ * E2: 获取成本汇总(滑动窗口)
1496
+ */
1497
+ getCostSummary(tenantId, period) {
1498
+ const now = Date.now();
1499
+ const periodMs = {
1500
+ "1h": 36e5,
1501
+ "24h": 864e5,
1502
+ "7d": 6048e5,
1503
+ "30d": 2592e6
1504
+ };
1505
+ const startTime = now - (periodMs[period] || 864e5);
1506
+ const filtered = this.records.filter((r) => r.tenantId === tenantId && r.timestamp >= startTime);
1507
+ const byCategory = {
1508
+ llm_inference: 0,
1509
+ tool_call: 0,
1510
+ human_review: 0,
1511
+ storage: 0,
1512
+ network: 0,
1513
+ compute: 0,
1514
+ other: 0
1515
+ };
1516
+ const byAgent = {};
1517
+ const byTool = {};
1518
+ let totalCostUsd = 0;
1519
+ for (const r of filtered) {
1520
+ totalCostUsd += r.costUsd;
1521
+ byCategory[r.category] = (byCategory[r.category] || 0) + r.costUsd;
1522
+ byAgent[r.agentId] = (byAgent[r.agentId] || 0) + r.costUsd;
1523
+ if (r.toolName) {
1524
+ byTool[r.toolName] = (byTool[r.toolName] || 0) + r.costUsd;
1525
+ }
1526
+ }
1527
+ this.audit("summary_generated", tenantId, { period, totalCostUsd, recordCount: filtered.length });
1528
+ return {
1529
+ period,
1530
+ totalCostUsd,
1531
+ byCategory,
1532
+ byAgent,
1533
+ byTool,
1534
+ recordCount: filtered.length,
1535
+ avgCostPerAction: filtered.length > 0 ? totalCostUsd / filtered.length : 0,
1536
+ startTime,
1537
+ endTime: now
1538
+ };
1539
+ }
1540
+ /**
1541
+ * E7: getDailyCostStats — 按天统计
1542
+ */
1543
+ getDailyCostStats(tenantId, days = 30) {
1544
+ const now = Date.now();
1545
+ const startTime = now - days * 864e5;
1546
+ const filtered = this.records.filter((r) => r.tenantId === tenantId && r.timestamp >= startTime);
1547
+ const dailyMap = /* @__PURE__ */ new Map();
1548
+ for (const r of filtered) {
1549
+ const date = new Date(r.timestamp).toISOString().split("T")[0];
1550
+ if (!dailyMap.has(date)) {
1551
+ dailyMap.set(date, { records: [], agents: /* @__PURE__ */ new Set() });
1552
+ }
1553
+ const day = dailyMap.get(date);
1554
+ day.records.push(r);
1555
+ day.agents.add(r.agentId);
1556
+ }
1557
+ const budget = this.budgets.get(tenantId) ?? this.config.defaultBudgetUsd;
1558
+ const dailyBudget = budget / 30;
1559
+ return Array.from(dailyMap.entries()).map(([date, { records, agents }]) => {
1560
+ const byCategory = {
1561
+ llm_inference: 0,
1562
+ tool_call: 0,
1563
+ human_review: 0,
1564
+ storage: 0,
1565
+ network: 0,
1566
+ compute: 0,
1567
+ other: 0
1568
+ };
1569
+ let totalCostUsd = 0;
1570
+ for (const r of records) {
1571
+ totalCostUsd += r.costUsd;
1572
+ byCategory[r.category] = (byCategory[r.category] || 0) + r.costUsd;
1573
+ }
1574
+ return {
1575
+ date,
1576
+ totalCostUsd,
1577
+ byCategory,
1578
+ actionCount: records.length,
1579
+ uniqueAgents: agents.size,
1580
+ budgetUtilization: dailyBudget > 0 ? totalCostUsd / dailyBudget : 0
1581
+ };
1582
+ }).sort((a, b) => a.date.localeCompare(b.date));
1583
+ }
1584
+ /**
1585
+ * E9: 计算工具调用成本
1586
+ */
1587
+ calculateToolCost(toolName, tokenCount) {
1588
+ const config = this.toolCostMap.get(toolName);
1589
+ if (!config) return 1e-3;
1590
+ let cost = config.baseCostUsd + config.perCallCostUsd;
1591
+ if (tokenCount && config.perTokenCostUsd) {
1592
+ cost += tokenCount * config.perTokenCostUsd;
1593
+ }
1594
+ if (config.maxCostPerCallUsd) {
1595
+ cost = Math.min(cost, config.maxCostPerCallUsd);
1596
+ }
1597
+ return cost;
1598
+ }
1599
+ /**
1600
+ * E10: 计算人工审批成本
1601
+ */
1602
+ calculateHumanReviewCost(waitTimeMs, reviewTimeMs) {
1603
+ const totalTimeMs = waitTimeMs + reviewTimeMs;
1604
+ const hours = totalTimeMs / 36e5;
1605
+ const costUsd = hours * this.config.humanReviewHourlyRateUsd;
1606
+ return {
1607
+ reviewId: `review_${Date.now()}`,
1608
+ reviewerType: "human",
1609
+ waitTimeMs,
1610
+ reviewTimeMs,
1611
+ costUsd: Math.round(costUsd * 1e4) / 1e4,
1612
+ hourlyRateUsd: this.config.humanReviewHourlyRateUsd
1613
+ };
1614
+ }
1615
+ /**
1616
+ * 设置租户预算
1617
+ */
1618
+ setBudget(tenantId, budgetUsd) {
1619
+ this.budgets.set(tenantId, budgetUsd);
1620
+ }
1621
+ /**
1622
+ * 获取租户预算使用率
1623
+ */
1624
+ getBudgetUtilization(tenantId) {
1625
+ const budget = this.budgets.get(tenantId) ?? this.config.defaultBudgetUsd;
1626
+ const summary = this.getCostSummary(tenantId, "30d");
1627
+ return {
1628
+ used: summary.totalCostUsd,
1629
+ limit: budget,
1630
+ utilization: budget > 0 ? summary.totalCostUsd / budget : 0
1631
+ };
1632
+ }
1633
+ // ============================================
1634
+ // 私有方法
1635
+ // ============================================
1636
+ checkBudget(tenantId, agentId, action) {
1637
+ const budget = this.budgets.get(tenantId) ?? this.config.defaultBudgetUsd;
1638
+ const summary = this.getCostSummary(tenantId, "30d");
1639
+ const utilization = budget > 0 ? summary.totalCostUsd / budget : 0;
1640
+ if (utilization >= 1) {
1641
+ const event = {
1642
+ code: "BUDGET_EXCEEDED",
1643
+ tenantId,
1644
+ agentId,
1645
+ action,
1646
+ currentCostUsd: summary.totalCostUsd,
1647
+ budgetLimitUsd: budget,
1648
+ overage: summary.totalCostUsd - budget,
1649
+ period: "30d",
1650
+ timestamp: Date.now(),
1651
+ severity: "blocked"
1652
+ };
1653
+ this.audit("budget_exceeded", tenantId, { event });
1654
+ if (this.config.onBudgetExceeded) this.config.onBudgetExceeded(event);
1655
+ return event;
1656
+ }
1657
+ if (utilization >= this.config.criticalThreshold) {
1658
+ this.audit("budget_critical", tenantId, { utilization, budget });
1659
+ } else if (utilization >= this.config.warningThreshold) {
1660
+ this.audit("budget_warning", tenantId, { utilization, budget });
1661
+ }
1662
+ return null;
1663
+ }
1664
+ audit(type, tenantId, details) {
1665
+ if (this.config.onAudit) {
1666
+ this.config.onAudit({ type, tenantId, details, timestamp: Date.now() });
1667
+ }
1668
+ }
1669
+ };
1670
+ function createCostGateEnhanced(config) {
1671
+ return new CostGateEnhancedEngine(config);
1672
+ }
1673
+
1674
+ // src/budgetMultiLevel.ts
1675
+ var DEFAULT_ALERT_RULES = [
1676
+ { id: "warn_80", threshold: 0.8, severity: "warning", action: "notify", cooldownMs: 36e5 },
1677
+ { id: "crit_95", threshold: 0.95, severity: "critical", action: "throttle", cooldownMs: 18e5 },
1678
+ { id: "block_100", threshold: 1, severity: "critical", action: "block", cooldownMs: 3e5 }
1679
+ ];
1680
+ var DEFAULT_CONFIG4 = {
1681
+ defaultAlertRules: DEFAULT_ALERT_RULES,
1682
+ trendWindowDays: 30,
1683
+ onAlert: void 0,
1684
+ onAudit: void 0
1685
+ };
1686
+ var MultiLevelBudgetEngine = class {
1687
+ nodes = /* @__PURE__ */ new Map();
1688
+ spendHistory = [];
1689
+ config;
1690
+ constructor(config = {}) {
1691
+ this.config = { ...DEFAULT_CONFIG4, ...config };
1692
+ }
1693
+ /**
1694
+ * F6: 创建预算节点
1695
+ */
1696
+ createNode(node) {
1697
+ const budgetNode = {
1698
+ ...node,
1699
+ spentUsd: 0,
1700
+ children: [],
1701
+ alertRules: node.alertRules ?? [...this.config.defaultAlertRules]
1702
+ };
1703
+ this.nodes.set(budgetNode.id, budgetNode);
1704
+ if (node.parentId) {
1705
+ const parent = this.nodes.get(node.parentId);
1706
+ if (parent) {
1707
+ parent.children.push(budgetNode.id);
1708
+ }
1709
+ }
1710
+ return budgetNode;
1711
+ }
1712
+ /**
1713
+ * F6: 记录支出(向上冒泡到所有父级)
1714
+ */
1715
+ recordSpend(nodeId, amount) {
1716
+ const alerts = [];
1717
+ let current = this.nodes.get(nodeId);
1718
+ while (current) {
1719
+ current.spentUsd += amount;
1720
+ this.spendHistory.push({ nodeId: current.id, amount, timestamp: Date.now() });
1721
+ const nodeAlerts = this.checkAlerts(current);
1722
+ alerts.push(...nodeAlerts);
1723
+ current = current.parentId ? this.nodes.get(current.parentId) : void 0;
1724
+ }
1725
+ return alerts;
1726
+ }
1727
+ /**
1728
+ * F6: 获取节点预算状态(含子节点汇总)
1729
+ */
1730
+ getNodeStatus(nodeId) {
1731
+ const node = this.nodes.get(nodeId);
1732
+ if (!node) return null;
1733
+ const childrenSpent = this.getChildrenSpent(nodeId);
1734
+ const utilization = node.budgetUsd > 0 ? node.spentUsd / node.budgetUsd : 0;
1735
+ return {
1736
+ node,
1737
+ utilization,
1738
+ childrenSpent,
1739
+ remaining: Math.max(0, node.budgetUsd - node.spentUsd)
1740
+ };
1741
+ }
1742
+ /**
1743
+ * F7: 预测预算耗尽日期
1744
+ */
1745
+ predictExhaustion(nodeId) {
1746
+ const node = this.nodes.get(nodeId);
1747
+ if (!node || node.spentUsd === 0) return null;
1748
+ const remaining = node.budgetUsd - node.spentUsd;
1749
+ if (remaining <= 0) return (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
1750
+ const sevenDaysAgo = Date.now() - 7 * 864e5;
1751
+ const recentSpends = this.spendHistory.filter(
1752
+ (s) => s.nodeId === nodeId && s.timestamp >= sevenDaysAgo
1753
+ );
1754
+ const recentTotal = recentSpends.reduce((sum, s) => sum + s.amount, 0);
1755
+ const dailyRate = recentTotal / 7;
1756
+ if (dailyRate <= 0) return null;
1757
+ const daysRemaining = remaining / dailyRate;
1758
+ const exhaustionDate = new Date(Date.now() + daysRemaining * 864e5);
1759
+ return exhaustionDate.toISOString().split("T")[0];
1760
+ }
1761
+ /**
1762
+ * F8: 生成成本报告
1763
+ */
1764
+ generateReport(rootNodeId) {
1765
+ const nodes = rootNodeId ? this.getSubtree(rootNodeId) : Array.from(this.nodes.values());
1766
+ const byLevel = {
1767
+ organization: { budget: 0, spent: 0, count: 0 },
1768
+ team: { budget: 0, spent: 0, count: 0 },
1769
+ project: { budget: 0, spent: 0, count: 0 },
1770
+ agent: { budget: 0, spent: 0, count: 0 }
1771
+ };
1772
+ let totalBudget = 0;
1773
+ let totalSpent = 0;
1774
+ for (const n of nodes) {
1775
+ byLevel[n.level].budget += n.budgetUsd;
1776
+ byLevel[n.level].spent += n.spentUsd;
1777
+ byLevel[n.level].count++;
1778
+ if (n.children.length === 0) {
1779
+ totalBudget += n.budgetUsd;
1780
+ totalSpent += n.spentUsd;
1781
+ }
1782
+ }
1783
+ const topSpenders = nodes.sort((a, b) => b.spentUsd - a.spentUsd).slice(0, 10).map((n) => ({ id: n.id, name: n.name, level: n.level, spent: n.spentUsd }));
1784
+ const trend = this.generateTrend(rootNodeId);
1785
+ return {
1786
+ reportId: `report_${Date.now()}`,
1787
+ generatedAt: Date.now(),
1788
+ period: { start: Date.now() - this.config.trendWindowDays * 864e5, end: Date.now() },
1789
+ totalBudgetUsd: totalBudget,
1790
+ totalSpentUsd: totalSpent,
1791
+ utilization: totalBudget > 0 ? totalSpent / totalBudget : 0,
1792
+ byLevel,
1793
+ topSpenders,
1794
+ alerts: [],
1795
+ trend
1796
+ };
1797
+ }
1798
+ /**
1799
+ * 获取所有节点
1800
+ */
1801
+ listNodes(level) {
1802
+ const all = Array.from(this.nodes.values());
1803
+ return level ? all.filter((n) => n.level === level) : all;
1804
+ }
1805
+ // ============================================
1806
+ // 私有方法
1807
+ // ============================================
1808
+ checkAlerts(node) {
1809
+ const alerts = [];
1810
+ const utilization = node.budgetUsd > 0 ? node.spentUsd / node.budgetUsd : 0;
1811
+ for (const rule of node.alertRules) {
1812
+ if (utilization >= rule.threshold) {
1813
+ if (rule.lastTriggeredAt && Date.now() - rule.lastTriggeredAt < rule.cooldownMs) {
1814
+ continue;
1815
+ }
1816
+ rule.lastTriggeredAt = Date.now();
1817
+ const alert = {
1818
+ ruleId: rule.id,
1819
+ nodeId: node.id,
1820
+ nodeName: node.name,
1821
+ level: node.level,
1822
+ severity: rule.severity,
1823
+ action: rule.action,
1824
+ utilization,
1825
+ budgetUsd: node.budgetUsd,
1826
+ spentUsd: node.spentUsd,
1827
+ remainingUsd: Math.max(0, node.budgetUsd - node.spentUsd),
1828
+ predictedExhaustionDate: this.predictExhaustion(node.id) ?? void 0,
1829
+ timestamp: Date.now()
1830
+ };
1831
+ alerts.push(alert);
1832
+ if (this.config.onAlert) this.config.onAlert(alert);
1833
+ }
1834
+ }
1835
+ return alerts;
1836
+ }
1837
+ getChildrenSpent(nodeId) {
1838
+ const node = this.nodes.get(nodeId);
1839
+ if (!node) return 0;
1840
+ let total = 0;
1841
+ for (const childId of node.children) {
1842
+ const child = this.nodes.get(childId);
1843
+ if (child) {
1844
+ total += child.spentUsd;
1845
+ }
1846
+ }
1847
+ return total;
1848
+ }
1849
+ getSubtree(nodeId) {
1850
+ const result = [];
1851
+ const queue = [nodeId];
1852
+ while (queue.length > 0) {
1853
+ const id = queue.shift();
1854
+ const node = this.nodes.get(id);
1855
+ if (node) {
1856
+ result.push(node);
1857
+ queue.push(...node.children);
1858
+ }
1859
+ }
1860
+ return result;
1861
+ }
1862
+ generateTrend(rootNodeId) {
1863
+ const nodeIds = rootNodeId ? new Set(this.getSubtree(rootNodeId).map((n) => n.id)) : null;
1864
+ const startTime = Date.now() - this.config.trendWindowDays * 864e5;
1865
+ const filtered = this.spendHistory.filter((s) => {
1866
+ if (s.timestamp < startTime) return false;
1867
+ if (nodeIds && !nodeIds.has(s.nodeId)) return false;
1868
+ return true;
1869
+ });
1870
+ const dailyMap = /* @__PURE__ */ new Map();
1871
+ for (const s of filtered) {
1872
+ const date = new Date(s.timestamp).toISOString().split("T")[0];
1873
+ dailyMap.set(date, (dailyMap.get(date) ?? 0) + s.amount);
1874
+ }
1875
+ return Array.from(dailyMap.entries()).map(([date, spent]) => ({ date, spent })).sort((a, b) => a.date.localeCompare(b.date));
1876
+ }
1877
+ };
1878
+ function createMultiLevelBudget(config) {
1879
+ return new MultiLevelBudgetEngine(config);
1880
+ }
1881
+
1882
+ // src/evolutionChannel.ts
1883
+ var DEFAULT_CONFIG5 = {
1884
+ maxVersions: 50,
1885
+ canaryMinDurationMs: 36e5,
1886
+ // 1 小时
1887
+ autoPromoteThreshold: 0.95,
1888
+ onAudit: void 0
1889
+ };
1890
+ var EvolutionChannelEngine = class {
1891
+ versions = /* @__PURE__ */ new Map();
1892
+ activeVersionId = null;
1893
+ canaryVersionId = null;
1894
+ abTests = /* @__PURE__ */ new Map();
1895
+ config;
1896
+ constructor(config = {}) {
1897
+ this.config = { ...DEFAULT_CONFIG5, ...config };
1898
+ }
1899
+ /**
1900
+ * 发布新策略版本
1901
+ */
1902
+ publish(version) {
1903
+ if (this.versions.size >= this.config.maxVersions) {
1904
+ this.cleanupOldVersions();
1905
+ }
1906
+ version.status = "draft";
1907
+ version.createdAt = Date.now();
1908
+ this.versions.set(version.id, version);
1909
+ this.audit("publish", version.id, version.version, version.createdBy);
1910
+ return version;
1911
+ }
1912
+ /**
1913
+ * 启动灰度发布
1914
+ */
1915
+ startCanary(versionId, percent, actor) {
1916
+ const version = this.versions.get(versionId);
1917
+ if (!version || version.status !== "draft") return false;
1918
+ if (percent < 1 || percent > 99) return false;
1919
+ version.status = "canary";
1920
+ version.canaryPercent = percent;
1921
+ this.canaryVersionId = versionId;
1922
+ this.audit("canary_start", versionId, version.version, actor, { percent });
1923
+ return true;
1924
+ }
1925
+ /**
1926
+ * 灰度晋升为正式版本
1927
+ */
1928
+ promoteCanary(actor) {
1929
+ if (!this.canaryVersionId) return false;
1930
+ const canary = this.versions.get(this.canaryVersionId);
1931
+ if (!canary || canary.status !== "canary") return false;
1932
+ const elapsed = Date.now() - canary.createdAt;
1933
+ if (elapsed < this.config.canaryMinDurationMs) return false;
1934
+ if (this.activeVersionId) {
1935
+ const old = this.versions.get(this.activeVersionId);
1936
+ if (old) old.status = "deprecated";
1937
+ }
1938
+ canary.status = "active";
1939
+ canary.canaryPercent = 100;
1940
+ this.activeVersionId = this.canaryVersionId;
1941
+ this.canaryVersionId = null;
1942
+ this.audit("canary_promote", canary.id, canary.version, actor);
1943
+ return true;
1944
+ }
1945
+ /**
1946
+ * 灰度回滚
1947
+ */
1948
+ rollbackCanary(actor) {
1949
+ if (!this.canaryVersionId) return false;
1950
+ const canary = this.versions.get(this.canaryVersionId);
1951
+ if (!canary) return false;
1952
+ canary.status = "rollback";
1953
+ canary.canaryPercent = 0;
1954
+ this.canaryVersionId = null;
1955
+ this.audit("canary_rollback", canary.id, canary.version, actor);
1956
+ return true;
1957
+ }
1958
+ /**
1959
+ * 路由决策:根据灰度百分比选择策略版本
1960
+ */
1961
+ resolveVersion(requestHash) {
1962
+ if (this.canaryVersionId) {
1963
+ const canary = this.versions.get(this.canaryVersionId);
1964
+ if (canary && canary.status === "canary") {
1965
+ const hash = requestHash ?? Math.random() * 100;
1966
+ if (hash % 100 < canary.canaryPercent) {
1967
+ return canary;
1968
+ }
1969
+ }
1970
+ }
1971
+ if (this.activeVersionId) {
1972
+ return this.versions.get(this.activeVersionId) ?? null;
1973
+ }
1974
+ return null;
1975
+ }
1976
+ /**
1977
+ * 启动 A/B 测试
1978
+ */
1979
+ startABTest(testId, controlId, treatmentId, trafficSplit, actor) {
1980
+ const control = this.versions.get(controlId);
1981
+ const treatment = this.versions.get(treatmentId);
1982
+ if (!control || !treatment) return null;
1983
+ const test = {
1984
+ id: testId,
1985
+ controlVersionId: controlId,
1986
+ treatmentVersionId: treatmentId,
1987
+ trafficSplit: Math.max(1, Math.min(99, trafficSplit)),
1988
+ startedAt: Date.now(),
1989
+ status: "running",
1990
+ metrics: {
1991
+ controlDecisions: 0,
1992
+ treatmentDecisions: 0,
1993
+ controlAllowRate: 0,
1994
+ treatmentAllowRate: 0,
1995
+ controlAvgLatencyMs: 0,
1996
+ treatmentAvgLatencyMs: 0
1997
+ }
1998
+ };
1999
+ this.abTests.set(testId, test);
2000
+ this.audit("ab_test_start", testId, `${control.version} vs ${treatment.version}`, actor, { trafficSplit });
2001
+ return test;
2002
+ }
2003
+ /**
2004
+ * A/B 测试路由
2005
+ */
2006
+ resolveABTest(testId, requestHash) {
2007
+ const test = this.abTests.get(testId);
2008
+ if (!test || test.status !== "running") return null;
2009
+ const hash = requestHash ?? Math.random() * 100;
2010
+ const isTreatment = hash % 100 < test.trafficSplit;
2011
+ const versionId = isTreatment ? test.treatmentVersionId : test.controlVersionId;
2012
+ const version = this.versions.get(versionId);
2013
+ if (!version) return null;
2014
+ return { version, group: isTreatment ? "treatment" : "control" };
2015
+ }
2016
+ /**
2017
+ * 结束 A/B 测试
2018
+ */
2019
+ endABTest(testId, actor) {
2020
+ const test = this.abTests.get(testId);
2021
+ if (!test) return null;
2022
+ test.status = "completed";
2023
+ this.audit("ab_test_end", testId, "", actor, { metrics: test.metrics });
2024
+ return test;
2025
+ }
2026
+ /**
2027
+ * 获取所有版本
2028
+ */
2029
+ listVersions() {
2030
+ return Array.from(this.versions.values()).sort((a, b) => b.createdAt - a.createdAt);
2031
+ }
2032
+ /**
2033
+ * 获取当前 active 版本
2034
+ */
2035
+ getActiveVersion() {
2036
+ return this.activeVersionId ? this.versions.get(this.activeVersionId) ?? null : null;
2037
+ }
2038
+ // ============================================
2039
+ // 私有方法
2040
+ // ============================================
2041
+ cleanupOldVersions() {
2042
+ const deprecated = Array.from(this.versions.values()).filter((v) => v.status === "deprecated" || v.status === "rollback").sort((a, b) => a.createdAt - b.createdAt);
2043
+ if (deprecated.length > 0) {
2044
+ this.versions.delete(deprecated[0].id);
2045
+ }
2046
+ }
2047
+ audit(type, policyId, version, actor, details) {
2048
+ if (this.config.onAudit) {
2049
+ this.config.onAudit({ type, policyId, version, timestamp: Date.now(), actor, details });
2050
+ }
2051
+ }
2052
+ };
2053
+ function createEvolutionChannel(config) {
2054
+ return new EvolutionChannelEngine(config);
2055
+ }
2056
+
688
2057
  // src/index.ts
689
2058
  var DEFAULT_RULES = [
690
2059
  // --- HTTP Proxy: Dangerous outbound calls ---
@@ -919,7 +2288,7 @@ var RISK_SCORES = {
919
2288
  high: 70,
920
2289
  critical: 95
921
2290
  };
922
- var ENGINE_VERSION = "3.3.0";
2291
+ var ENGINE_VERSION = "3.4.0";
923
2292
  var ENGINE_VERSION_CHECK_URL = "https://api.sovr.inc/api/sovr/v1/version/check";
924
2293
  var ENGINE_TIER_LIMITS = {
925
2294
  free: { evaluationsPerMonth: 50, irreversibleAllowsPerMonth: 0 },
@@ -1175,13 +2544,32 @@ var index_default = PolicyEngine;
1175
2544
  // Annotate the CommonJS export names for ESM import in node:
1176
2545
  0 && (module.exports = {
1177
2546
  AdaptiveThresholdManager,
2547
+ AutoHardenEngine,
2548
+ CostGateEnhancedEngine,
1178
2549
  DEFAULT_RULES,
2550
+ EvolutionChannelEngine,
1179
2551
  FeatureSwitchesManager,
2552
+ MultiLevelBudgetEngine,
1180
2553
  PolicyEngine,
1181
2554
  PricingRulesEngine,
2555
+ RecalculationEngine,
1182
2556
  SOVR_FEATURE_SWITCHES,
2557
+ SemanticDriftDetectorEngine,
1183
2558
  compileFromJSON,
1184
2559
  compileRuleSet,
2560
+ createAutoHardenEngine,
2561
+ createCostGateEnhanced,
2562
+ createEvolutionChannel,
2563
+ createMultiLevelBudget,
2564
+ createRecalculationEngine,
2565
+ createSemanticDriftDetector,
2566
+ estimateCost,
1185
2567
  evaluateRules,
1186
- registerFunction
2568
+ getAccuracyStats,
2569
+ getModelPricingTable,
2570
+ getToolPricingTable,
2571
+ recordActualCost,
2572
+ registerFunction,
2573
+ updateModelPricing,
2574
+ updateToolPricing
1187
2575
  });