@sovr/engine 3.3.0 → 3.5.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,45 @@ 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
+ ContextAccelerator: () => ContextAccelerator,
26
+ CostGateEnhancedEngine: () => CostGateEnhancedEngine,
27
+ DEFAULT_CA_CONFIG: () => DEFAULT_CA_CONFIG,
28
+ DEFAULT_GE_CONFIG: () => DEFAULT_GE_CONFIG,
29
+ DEFAULT_HARD_RULES: () => DEFAULT_HARD_RULES,
24
30
  DEFAULT_RULES: () => DEFAULT_RULES,
31
+ DEFAULT_SCORING_WEIGHTS: () => DEFAULT_SCORING_WEIGHTS,
32
+ DEFAULT_TSA_CONFIG: () => DEFAULT_TSA_CONFIG,
33
+ EvolutionChannelEngine: () => EvolutionChannelEngine,
25
34
  FeatureSwitchesManager: () => FeatureSwitchesManager,
35
+ GovernanceEnhancer: () => GovernanceEnhancer,
36
+ MultiLevelBudgetEngine: () => MultiLevelBudgetEngine,
26
37
  PolicyEngine: () => PolicyEngine,
27
38
  PricingRulesEngine: () => PricingRulesEngine,
39
+ RecalculationEngine: () => RecalculationEngine,
28
40
  SOVR_FEATURE_SWITCHES: () => SOVR_FEATURE_SWITCHES,
41
+ SemanticDriftDetectorEngine: () => SemanticDriftDetectorEngine,
42
+ TimeSeriesAggregator: () => TimeSeriesAggregator,
43
+ TwoPhaseRouter: () => TwoPhaseRouter,
44
+ ValuationModel: () => ValuationModel,
29
45
  compileFromJSON: () => compileFromJSON,
30
46
  compileRuleSet: () => compileRuleSet,
47
+ createAutoHardenEngine: () => createAutoHardenEngine,
48
+ createCostGateEnhanced: () => createCostGateEnhanced,
49
+ createEvolutionChannel: () => createEvolutionChannel,
50
+ createMultiLevelBudget: () => createMultiLevelBudget,
51
+ createRecalculationEngine: () => createRecalculationEngine,
52
+ createSemanticDriftDetector: () => createSemanticDriftDetector,
31
53
  default: () => index_default,
54
+ estimateCost: () => estimateCost,
32
55
  evaluateRules: () => evaluateRules,
33
- registerFunction: () => registerFunction
56
+ getAccuracyStats: () => getAccuracyStats,
57
+ getModelPricingTable: () => getModelPricingTable,
58
+ getToolPricingTable: () => getToolPricingTable,
59
+ recordActualCost: () => recordActualCost,
60
+ registerFunction: () => registerFunction,
61
+ updateModelPricing: () => updateModelPricing,
62
+ updateToolPricing: () => updateToolPricing
34
63
  });
35
64
  module.exports = __toCommonJS(index_exports);
36
65
 
@@ -685,6 +714,2556 @@ var PricingRulesEngine = class {
685
714
  }
686
715
  };
687
716
 
717
+ // src/recalculationEngine.ts
718
+ var idCounter = 0;
719
+ function genId(prefix) {
720
+ return `${prefix}_${Date.now()}_${++idCounter}`;
721
+ }
722
+ function simpleHash(data) {
723
+ let hash = 0;
724
+ for (let i = 0; i < data.length; i++) {
725
+ const char = data.charCodeAt(i);
726
+ hash = (hash << 5) - hash + char;
727
+ hash = hash & hash;
728
+ }
729
+ return "h_" + Math.abs(hash).toString(16).padStart(8, "0");
730
+ }
731
+ var RecalculationEngine = class {
732
+ tasks = /* @__PURE__ */ new Map();
733
+ consistencyResults = /* @__PURE__ */ new Map();
734
+ snapshots = /* @__PURE__ */ new Map();
735
+ handlers = /* @__PURE__ */ new Map();
736
+ config;
737
+ constructor(config = {}) {
738
+ this.config = { maxRangeDays: 30, ...config };
739
+ }
740
+ /** G3: Trigger recalculation */
741
+ triggerRecalculation(input) {
742
+ if (input.fromTs >= input.toTs) throw new Error("fromTs must be before toTs");
743
+ const maxMs = this.config.maxRangeDays * 864e5;
744
+ if (input.toTs - input.fromTs > maxMs) throw new Error(`Range exceeds ${this.config.maxRangeDays} days`);
745
+ const task = {
746
+ id: genId("recalc"),
747
+ tenantId: input.tenantId,
748
+ triggerType: input.triggerType,
749
+ triggeredBy: input.triggeredBy,
750
+ reason: input.reason,
751
+ fromTs: input.fromTs,
752
+ toTs: input.toTs,
753
+ granularity: input.granularity || "all",
754
+ incremental: input.incremental || false,
755
+ incrementalCheckpoint: input.incrementalCheckpoint,
756
+ status: "pending",
757
+ progress: 0,
758
+ bucketsProcessed: 0,
759
+ rowsUpserted: 0,
760
+ createdAt: Date.now(),
761
+ traceId: genId("trace")
762
+ };
763
+ this.tasks.set(task.id, task);
764
+ this.audit("recalc.triggered", { taskId: task.id, triggerType: task.triggerType, reason: task.reason });
765
+ return task;
766
+ }
767
+ /** Execute recalculation task */
768
+ async executeTask(taskId) {
769
+ const task = this.tasks.get(taskId);
770
+ if (!task) throw new Error(`Task not found: ${taskId}`);
771
+ if (task.status !== "pending") throw new Error(`Task not pending: ${task.status}`);
772
+ task.status = "running";
773
+ task.startedAt = Date.now();
774
+ this.audit("recalc.started", { taskId: task.id });
775
+ try {
776
+ const preSnapshot = this.createSnapshot(task.tenantId, "pre_recalc", task.id);
777
+ const handler = this.handlers.get(task.granularity);
778
+ if (handler) {
779
+ const result = await handler(task);
780
+ task.bucketsProcessed = result.bucketsProcessed;
781
+ task.rowsUpserted = result.rowsUpserted;
782
+ const postSnapshot = this.createSnapshot(task.tenantId, "post_recalc", task.id, result.metrics);
783
+ task.consistencyResult = this.verifyConsistency(task.id, preSnapshot, postSnapshot, result.metrics);
784
+ } else {
785
+ const segmentMs = task.granularity === "5m" ? 3e5 : task.granularity === "1h" ? 36e5 : task.granularity === "1d" ? 864e5 : 36e5;
786
+ const totalSegments = Math.ceil((task.toTs - task.fromTs) / segmentMs);
787
+ task.bucketsProcessed = totalSegments;
788
+ task.progress = 100;
789
+ }
790
+ task.status = "completed";
791
+ task.completedAt = Date.now();
792
+ task.progress = 100;
793
+ this.audit("recalc.completed", {
794
+ taskId: task.id,
795
+ bucketsProcessed: task.bucketsProcessed,
796
+ durationMs: task.completedAt - (task.startedAt || 0),
797
+ consistencyRate: task.consistencyResult?.consistencyRate
798
+ });
799
+ return task;
800
+ } catch (error) {
801
+ task.status = "failed";
802
+ task.error = error instanceof Error ? error.message : "Unknown error";
803
+ task.completedAt = Date.now();
804
+ this.audit("recalc.failed", { taskId: task.id, error: task.error });
805
+ return task;
806
+ }
807
+ }
808
+ /** G4: Verify consistency */
809
+ verifyConsistency(taskId, preSnapshot, postSnapshot, recalculatedMetrics) {
810
+ const mismatches = [];
811
+ const metrics = recalculatedMetrics || postSnapshot.metrics;
812
+ let totalComparisons = 0;
813
+ let matchCount = 0;
814
+ for (const [metric, recalcValue] of Object.entries(metrics)) {
815
+ const currentValue = preSnapshot.metrics[metric];
816
+ if (currentValue === void 0) continue;
817
+ totalComparisons++;
818
+ const deviation = Math.abs(recalcValue - currentValue);
819
+ const deviationPercent = currentValue !== 0 ? deviation / Math.abs(currentValue) * 100 : recalcValue !== 0 ? 100 : 0;
820
+ if (deviationPercent < 0.01) {
821
+ matchCount++;
822
+ } else {
823
+ mismatches.push({
824
+ metric,
825
+ bucket: `${preSnapshot.id} \u2192 ${postSnapshot.id}`,
826
+ currentValue,
827
+ recalculatedValue: recalcValue,
828
+ deviation,
829
+ deviationPercent: Math.round(deviationPercent * 100) / 100,
830
+ severity: deviationPercent > 10 ? "critical" : deviationPercent > 5 ? "high" : deviationPercent > 1 ? "medium" : "low"
831
+ });
832
+ }
833
+ }
834
+ const consistencyRate = totalComparisons > 0 ? Math.round(matchCount / totalComparisons * 1e4) / 100 : 100;
835
+ const verificationHash = simpleHash(JSON.stringify({ taskId, pre: preSnapshot.hash, post: postSnapshot.hash, mismatches }));
836
+ const result = {
837
+ id: genId("cr"),
838
+ taskId,
839
+ status: mismatches.length === 0 ? "consistent" : consistencyRate > 95 ? "partial" : "inconsistent",
840
+ totalComparisons,
841
+ matchCount,
842
+ mismatchCount: mismatches.length,
843
+ consistencyRate,
844
+ mismatches,
845
+ verifiedAt: Date.now(),
846
+ verificationHash
847
+ };
848
+ this.consistencyResults.set(result.id, result);
849
+ this.audit("recalc.consistency_check", { taskId, consistencyRate, mismatchCount: mismatches.length, status: result.status });
850
+ return result;
851
+ }
852
+ /** G5: Incremental recalculation */
853
+ triggerIncremental(input) {
854
+ 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));
855
+ const last = completed[0];
856
+ const fromTs = last ? last.toTs : Date.now() - 864e5;
857
+ return this.triggerRecalculation({
858
+ tenantId: input.tenantId,
859
+ triggerType: "manual",
860
+ triggeredBy: input.triggeredBy,
861
+ reason: input.reason,
862
+ fromTs,
863
+ toTs: Date.now(),
864
+ granularity: input.granularity,
865
+ incremental: true,
866
+ incrementalCheckpoint: last?.id
867
+ });
868
+ }
869
+ /** Create aggregate snapshot */
870
+ createSnapshot(tenantId, snapshotType, taskId, metrics) {
871
+ const m = metrics || {};
872
+ const snapshot = {
873
+ id: genId("snap"),
874
+ tenantId,
875
+ snapshotType,
876
+ taskId,
877
+ metrics: m,
878
+ hash: simpleHash(JSON.stringify(m)),
879
+ createdAt: Date.now()
880
+ };
881
+ this.snapshots.set(snapshot.id, snapshot);
882
+ return snapshot;
883
+ }
884
+ /** Register recalculation handler */
885
+ registerHandler(granularity, handler) {
886
+ this.handlers.set(granularity, handler);
887
+ }
888
+ /** Query functions */
889
+ getTask(taskId) {
890
+ return this.tasks.get(taskId);
891
+ }
892
+ getTasks(tenantId, limit = 20) {
893
+ return Array.from(this.tasks.values()).filter((t) => t.tenantId === tenantId).sort((a, b) => b.createdAt - a.createdAt).slice(0, limit);
894
+ }
895
+ getConsistencyResult(taskId) {
896
+ return Array.from(this.consistencyResults.values()).find((r) => r.taskId === taskId);
897
+ }
898
+ getSnapshot(snapshotId) {
899
+ return this.snapshots.get(snapshotId);
900
+ }
901
+ cancelTask(taskId) {
902
+ const task = this.tasks.get(taskId);
903
+ if (!task || task.status !== "pending") return false;
904
+ task.status = "cancelled";
905
+ return true;
906
+ }
907
+ audit(type, details) {
908
+ if (this.config.onAudit) {
909
+ this.config.onAudit({ type, details, timestamp: Date.now() });
910
+ }
911
+ }
912
+ };
913
+ function createRecalculationEngine(config) {
914
+ return new RecalculationEngine(config);
915
+ }
916
+
917
+ // src/autoHarden.ts
918
+ var LEVEL_PRIORITY = {
919
+ normal: 0,
920
+ elevated: 1,
921
+ hardened: 2,
922
+ lockdown: 3
923
+ };
924
+ var DEFAULT_CONFIG = {
925
+ enabled: true,
926
+ levelMeasures: {
927
+ normal: [],
928
+ elevated: ["enhanced_audit", "alert_admin"],
929
+ hardened: ["gate_level_upgrade", "rate_limit_reduce", "enhanced_audit", "alert_admin"],
930
+ lockdown: ["gate_level_upgrade", "rate_limit_reduce", "enhanced_audit", "ip_block", "session_invalidate", "feature_disable", "alert_admin"]
931
+ },
932
+ autoRollbackMs: 30 * 60 * 1e3,
933
+ rateLimitReductionFactor: 0.25,
934
+ notifyAdmin: true
935
+ };
936
+ var idCounter2 = 0;
937
+ function genId2(prefix) {
938
+ return `${prefix}_${Date.now()}_${++idCounter2}`;
939
+ }
940
+ var AutoHardenEngine = class {
941
+ states = /* @__PURE__ */ new Map();
942
+ history = [];
943
+ config;
944
+ rollbackTimers = /* @__PURE__ */ new Map();
945
+ maxHistory = 1e3;
946
+ constructor(config = {}) {
947
+ this.config = { ...DEFAULT_CONFIG, ...config };
948
+ }
949
+ /** Get tenant harden state */
950
+ getState(tenantId) {
951
+ return this.states.get(tenantId) || { currentLevel: "normal", activeMeasures: [] };
952
+ }
953
+ /** Get current harden level */
954
+ getLevel(tenantId) {
955
+ return this.getState(tenantId).currentLevel;
956
+ }
957
+ /** Auto-harden (main entry) */
958
+ async harden(input) {
959
+ if (!this.config.enabled) throw new Error("AutoHarden is disabled");
960
+ const state = this.getState(input.tenantId);
961
+ const traceId = genId2("trace");
962
+ const targetLevel = input.targetLevel || this.determineLevel(
963
+ input.manipulationScore || 0,
964
+ input.reasonCodes || []
965
+ );
966
+ if (LEVEL_PRIORITY[targetLevel] <= LEVEL_PRIORITY[state.currentLevel]) {
967
+ const event2 = {
968
+ id: genId2("harden"),
969
+ tenantId: input.tenantId,
970
+ triggeredBy: input.triggeredBy,
971
+ reason: `Already at ${state.currentLevel}, target ${targetLevel} skipped`,
972
+ previousLevel: state.currentLevel,
973
+ newLevel: state.currentLevel,
974
+ measures: [],
975
+ createdAt: Date.now(),
976
+ rolledBack: false,
977
+ traceId
978
+ };
979
+ this.history.push(event2);
980
+ return event2;
981
+ }
982
+ const measures = this.applyMeasures(input.tenantId, targetLevel);
983
+ const previousLevel = state.currentLevel;
984
+ state.currentLevel = targetLevel;
985
+ state.activeMeasures = measures;
986
+ state.hardenedSince = Date.now();
987
+ if (this.config.autoRollbackMs > 0) {
988
+ state.expectedRollbackAt = Date.now() + this.config.autoRollbackMs;
989
+ this.scheduleAutoRollback(input.tenantId, this.config.autoRollbackMs);
990
+ }
991
+ this.states.set(input.tenantId, state);
992
+ const event = {
993
+ id: genId2("harden"),
994
+ tenantId: input.tenantId,
995
+ triggeredBy: input.triggeredBy,
996
+ reason: input.reason,
997
+ previousLevel,
998
+ newLevel: targetLevel,
999
+ measures,
1000
+ createdAt: Date.now(),
1001
+ rolledBack: false,
1002
+ traceId
1003
+ };
1004
+ this.history.push(event);
1005
+ if (this.history.length > this.maxHistory) this.history.shift();
1006
+ state.lastEvent = event;
1007
+ this.audit(event.rolledBack ? "HARDEN_ROLLBACK" : "HARDEN_ACTIVATED", {
1008
+ tenantId: event.tenantId,
1009
+ previousLevel,
1010
+ newLevel: targetLevel,
1011
+ measuresCount: measures.length,
1012
+ measures: measures.map((m) => m.type)
1013
+ });
1014
+ if (this.config.notifyAdmin && this.config.onNotifyAdmin) {
1015
+ try {
1016
+ await this.config.onNotifyAdmin(event);
1017
+ } catch {
1018
+ }
1019
+ }
1020
+ return event;
1021
+ }
1022
+ /** Manual rollback */
1023
+ async rollback(tenantId, rolledBackBy, reason) {
1024
+ const state = this.getState(tenantId);
1025
+ if (state.currentLevel === "normal") throw new Error("Already at normal level");
1026
+ const timer = this.rollbackTimers.get(tenantId);
1027
+ if (timer) {
1028
+ clearTimeout(timer);
1029
+ this.rollbackTimers.delete(tenantId);
1030
+ }
1031
+ const previousLevel = state.currentLevel;
1032
+ const event = {
1033
+ id: genId2("harden"),
1034
+ tenantId,
1035
+ triggeredBy: rolledBackBy,
1036
+ reason: reason || `Manual rollback from ${previousLevel}`,
1037
+ previousLevel,
1038
+ newLevel: "normal",
1039
+ measures: state.activeMeasures.map((m) => ({ ...m, rolledBackAt: Date.now() })),
1040
+ createdAt: Date.now(),
1041
+ rolledBack: true,
1042
+ rolledBackAt: Date.now(),
1043
+ traceId: genId2("trace")
1044
+ };
1045
+ state.currentLevel = "normal";
1046
+ state.activeMeasures = [];
1047
+ state.hardenedSince = void 0;
1048
+ state.expectedRollbackAt = void 0;
1049
+ state.lastEvent = event;
1050
+ this.states.set(tenantId, state);
1051
+ this.history.push(event);
1052
+ this.audit("HARDEN_ROLLBACK", { tenantId, previousLevel, rolledBackBy });
1053
+ return event;
1054
+ }
1055
+ /** Update config */
1056
+ updateConfig(config) {
1057
+ this.config = { ...this.config, ...config };
1058
+ return this.config;
1059
+ }
1060
+ /** Get config */
1061
+ getConfig() {
1062
+ return { ...this.config };
1063
+ }
1064
+ /** Get history */
1065
+ getHistory(tenantId, limit = 50) {
1066
+ const filtered = tenantId ? this.history.filter((e) => e.tenantId === tenantId) : this.history;
1067
+ return filtered.slice(-limit);
1068
+ }
1069
+ /** Get all active hardened states */
1070
+ getActiveStates() {
1071
+ const result = [];
1072
+ this.states.forEach((state, tenantId) => {
1073
+ if (state.currentLevel !== "normal") result.push({ tenantId, state });
1074
+ });
1075
+ return result;
1076
+ }
1077
+ /** Cleanup timers */
1078
+ destroy() {
1079
+ this.rollbackTimers.forEach((t) => clearTimeout(t));
1080
+ this.rollbackTimers.clear();
1081
+ }
1082
+ // Internal
1083
+ determineLevel(score, reasonCodes) {
1084
+ if (reasonCodes.some((c) => c.startsWith("CRIT_"))) return "lockdown";
1085
+ if (score >= 0.8) return "lockdown";
1086
+ if (score >= 0.5) return "hardened";
1087
+ if (score >= 0.3) return "elevated";
1088
+ return "normal";
1089
+ }
1090
+ applyMeasures(tenantId, level) {
1091
+ const types = this.config.levelMeasures[level];
1092
+ return types.map((type) => ({
1093
+ id: genId2("measure"),
1094
+ type,
1095
+ description: this.getMeasureDescription(type, level),
1096
+ applied: true,
1097
+ appliedAt: Date.now()
1098
+ }));
1099
+ }
1100
+ getMeasureDescription(type, level) {
1101
+ const d = {
1102
+ gate_level_upgrade: `Gate approval level upgraded to ${level}`,
1103
+ rate_limit_reduce: `Rate limit reduced to ${this.config.rateLimitReductionFactor * 100}%`,
1104
+ enhanced_audit: "Enhanced audit mode enabled (full recording)",
1105
+ ip_block: "Suspicious IPs blocked",
1106
+ session_invalidate: "All active sessions invalidated",
1107
+ feature_disable: "Non-essential features disabled",
1108
+ alert_admin: "Admin security alert sent"
1109
+ };
1110
+ return d[type] || type;
1111
+ }
1112
+ scheduleAutoRollback(tenantId, delayMs) {
1113
+ const existing = this.rollbackTimers.get(tenantId);
1114
+ if (existing) clearTimeout(existing);
1115
+ const timer = setTimeout(async () => {
1116
+ try {
1117
+ await this.rollback(tenantId, "system:auto_rollback", "Auto rollback after timeout");
1118
+ } catch {
1119
+ }
1120
+ this.rollbackTimers.delete(tenantId);
1121
+ }, delayMs);
1122
+ this.rollbackTimers.set(tenantId, timer);
1123
+ }
1124
+ audit(type, details) {
1125
+ if (this.config.onAudit) {
1126
+ this.config.onAudit({ type, details, timestamp: Date.now() });
1127
+ }
1128
+ }
1129
+ };
1130
+ function createAutoHardenEngine(config) {
1131
+ return new AutoHardenEngine(config);
1132
+ }
1133
+
1134
+ // src/costEstimator.ts
1135
+ var DEFAULT_MODEL_PRICING = [
1136
+ {
1137
+ modelId: "gpt-4o",
1138
+ modelName: "GPT-4o",
1139
+ inputPricePerKToken: 25e-4,
1140
+ outputPricePerKToken: 0.01,
1141
+ cachedInputPricePerKToken: 125e-5,
1142
+ maxContextLength: 128e3,
1143
+ updatedAt: /* @__PURE__ */ new Date("2025-01-01")
1144
+ },
1145
+ {
1146
+ modelId: "gpt-4o-mini",
1147
+ modelName: "GPT-4o Mini",
1148
+ inputPricePerKToken: 15e-5,
1149
+ outputPricePerKToken: 6e-4,
1150
+ cachedInputPricePerKToken: 75e-6,
1151
+ maxContextLength: 128e3,
1152
+ updatedAt: /* @__PURE__ */ new Date("2025-01-01")
1153
+ },
1154
+ {
1155
+ modelId: "claude-3.5-sonnet",
1156
+ modelName: "Claude 3.5 Sonnet",
1157
+ inputPricePerKToken: 3e-3,
1158
+ outputPricePerKToken: 0.015,
1159
+ cachedInputPricePerKToken: 3e-4,
1160
+ maxContextLength: 2e5,
1161
+ updatedAt: /* @__PURE__ */ new Date("2025-01-01")
1162
+ },
1163
+ {
1164
+ modelId: "claude-3.5-haiku",
1165
+ modelName: "Claude 3.5 Haiku",
1166
+ inputPricePerKToken: 8e-4,
1167
+ outputPricePerKToken: 4e-3,
1168
+ cachedInputPricePerKToken: 8e-5,
1169
+ maxContextLength: 2e5,
1170
+ updatedAt: /* @__PURE__ */ new Date("2025-01-01")
1171
+ },
1172
+ {
1173
+ modelId: "gemini-2.0-flash",
1174
+ modelName: "Gemini 2.0 Flash",
1175
+ inputPricePerKToken: 1e-4,
1176
+ outputPricePerKToken: 4e-4,
1177
+ maxContextLength: 1e6,
1178
+ updatedAt: /* @__PURE__ */ new Date("2025-01-01")
1179
+ }
1180
+ ];
1181
+ var DEFAULT_TOOL_PRICING = [
1182
+ { toolId: "web_search", toolName: "Web Search", costPerCall: 5e-3, multiplier: 1, updatedAt: /* @__PURE__ */ new Date() },
1183
+ { toolId: "code_exec", toolName: "Code Execution", costPerCall: 2e-3, multiplier: 1, updatedAt: /* @__PURE__ */ new Date() },
1184
+ { toolId: "file_read", toolName: "File Read", costPerCall: 1e-3, multiplier: 1, updatedAt: /* @__PURE__ */ new Date() },
1185
+ { toolId: "db_query", toolName: "Database Query", costPerCall: 3e-3, multiplier: 1, updatedAt: /* @__PURE__ */ new Date() },
1186
+ { toolId: "api_call", toolName: "External API Call", costPerCall: 0.01, multiplier: 1.5, updatedAt: /* @__PURE__ */ new Date() }
1187
+ ];
1188
+ var DEFAULT_HUMAN_RATES = [
1189
+ { level: "standard", hourlyRate: 50, avgReviewMinutes: 5 },
1190
+ { level: "senior", hourlyRate: 100, avgReviewMinutes: 10 },
1191
+ { level: "executive", hourlyRate: 200, avgReviewMinutes: 15 }
1192
+ ];
1193
+ var modelPricing = [...DEFAULT_MODEL_PRICING];
1194
+ var toolPricing = [...DEFAULT_TOOL_PRICING];
1195
+ var humanRates = [...DEFAULT_HUMAN_RATES];
1196
+ var accuracyRecords = [];
1197
+ var MAX_ACCURACY_RECORDS = 1e4;
1198
+ function estimateCost(request) {
1199
+ const id = `est_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1200
+ const model = modelPricing.find((m) => m.modelId === request.modelId) || modelPricing[0];
1201
+ const inputCost = request.estimatedInputTokens / 1e3 * model.inputPricePerKToken;
1202
+ const outputCost = request.estimatedOutputTokens / 1e3 * model.outputPricePerKToken;
1203
+ const modelCostTotal = inputCost + outputCost;
1204
+ const toolItems = [];
1205
+ let toolCostTotal = 0;
1206
+ if (request.toolCalls) {
1207
+ for (const tc of request.toolCalls) {
1208
+ const tool = toolPricing.find((t) => t.toolId === tc.toolId);
1209
+ if (tool) {
1210
+ const total = tc.estimatedCalls * tool.costPerCall * tool.multiplier;
1211
+ toolItems.push({
1212
+ toolId: tc.toolId,
1213
+ calls: tc.estimatedCalls,
1214
+ costPerCall: tool.costPerCall,
1215
+ total
1216
+ });
1217
+ toolCostTotal += total;
1218
+ }
1219
+ }
1220
+ }
1221
+ let humanCost = null;
1222
+ if (request.requiresHumanReview) {
1223
+ const rate = humanRates.find((r) => r.level === (request.humanReviewLevel || "standard")) || humanRates[0];
1224
+ const humanTotal = rate.avgReviewMinutes / 60 * rate.hourlyRate;
1225
+ humanCost = {
1226
+ level: rate.level,
1227
+ hourlyRate: rate.hourlyRate,
1228
+ estimatedMinutes: rate.avgReviewMinutes,
1229
+ total: humanTotal
1230
+ };
1231
+ }
1232
+ const totalCost = modelCostTotal + toolCostTotal + (humanCost?.total || 0);
1233
+ const avgDeviation = getAverageDeviation();
1234
+ const confidence = {
1235
+ low: totalCost * (1 - avgDeviation),
1236
+ high: totalCost * (1 + avgDeviation),
1237
+ level: Math.max(0, 1 - avgDeviation)
1238
+ };
1239
+ return {
1240
+ id,
1241
+ modelCost: {
1242
+ inputCost: Math.round(inputCost * 1e6) / 1e6,
1243
+ outputCost: Math.round(outputCost * 1e6) / 1e6,
1244
+ total: Math.round(modelCostTotal * 1e6) / 1e6
1245
+ },
1246
+ toolCost: {
1247
+ items: toolItems,
1248
+ total: Math.round(toolCostTotal * 1e6) / 1e6
1249
+ },
1250
+ humanCost,
1251
+ totalCost: Math.round(totalCost * 1e6) / 1e6,
1252
+ confidence,
1253
+ estimatedAt: /* @__PURE__ */ new Date()
1254
+ };
1255
+ }
1256
+ function recordActualCost(estimateId, actualCost) {
1257
+ const record = {
1258
+ estimateId,
1259
+ estimatedCost: 0,
1260
+ // 需要外部传入
1261
+ actualCost,
1262
+ deviation: 0,
1263
+ deviationPercent: 0,
1264
+ recordedAt: /* @__PURE__ */ new Date()
1265
+ };
1266
+ accuracyRecords.push(record);
1267
+ if (accuracyRecords.length > MAX_ACCURACY_RECORDS) accuracyRecords.shift();
1268
+ return record;
1269
+ }
1270
+ function getAverageDeviation() {
1271
+ if (accuracyRecords.length === 0) return 0.3;
1272
+ const deviations = accuracyRecords.filter((r) => r.estimatedCost > 0).map((r) => Math.abs(r.deviationPercent));
1273
+ if (deviations.length === 0) return 0.3;
1274
+ return deviations.reduce((sum, d) => sum + d, 0) / deviations.length / 100;
1275
+ }
1276
+ function updateModelPricing(pricing) {
1277
+ const index = modelPricing.findIndex((m) => m.modelId === pricing.modelId);
1278
+ if (index >= 0) {
1279
+ modelPricing[index] = pricing;
1280
+ } else {
1281
+ modelPricing.push(pricing);
1282
+ }
1283
+ }
1284
+ function updateToolPricing(pricing) {
1285
+ const index = toolPricing.findIndex((t) => t.toolId === pricing.toolId);
1286
+ if (index >= 0) {
1287
+ toolPricing[index] = pricing;
1288
+ } else {
1289
+ toolPricing.push(pricing);
1290
+ }
1291
+ }
1292
+ function getModelPricingTable() {
1293
+ return [...modelPricing];
1294
+ }
1295
+ function getToolPricingTable() {
1296
+ return [...toolPricing];
1297
+ }
1298
+ function getAccuracyStats() {
1299
+ const avgDev = getAverageDeviation();
1300
+ return {
1301
+ totalRecords: accuracyRecords.length,
1302
+ avgDeviation: avgDev,
1303
+ avgDeviationPercent: avgDev * 100,
1304
+ confidenceLevel: Math.max(0, 1 - avgDev)
1305
+ };
1306
+ }
1307
+
1308
+ // src/semanticDriftDetector.ts
1309
+ var DEFAULT_CONFIG2 = {
1310
+ lowThreshold: 0.1,
1311
+ mediumThreshold: 0.3,
1312
+ highThreshold: 0.5,
1313
+ criticalThreshold: 0.7,
1314
+ onDriftDetected: void 0,
1315
+ onAudit: void 0
1316
+ };
1317
+ var SemanticDriftDetectorEngine = class {
1318
+ fingerprints = /* @__PURE__ */ new Map();
1319
+ history = [];
1320
+ config;
1321
+ constructor(config = {}) {
1322
+ this.config = { ...DEFAULT_CONFIG2, ...config };
1323
+ }
1324
+ /**
1325
+ * 计算策略语义指纹
1326
+ */
1327
+ computeFingerprint(snapshot) {
1328
+ const rules = snapshot.rules;
1329
+ const resourceSet = [...new Set(rules.map((r) => r.resource))].sort();
1330
+ const actionSet = [...new Set(rules.map((r) => r.action))].sort();
1331
+ const fingerprint = {
1332
+ version: snapshot.version,
1333
+ hash: this.hashRules(rules),
1334
+ ruleCount: rules.length,
1335
+ allowCount: rules.filter((r) => r.decision === "ALLOW").length,
1336
+ denyCount: rules.filter((r) => r.decision === "DENY").length,
1337
+ reviewCount: rules.filter((r) => r.decision === "REVIEW").length,
1338
+ resourceSet,
1339
+ actionSet,
1340
+ conditionDepth: this.maxConditionDepth(rules),
1341
+ timestamp: Date.now()
1342
+ };
1343
+ this.fingerprints.set(snapshot.version, fingerprint);
1344
+ return fingerprint;
1345
+ }
1346
+ /**
1347
+ * 检测两个版本间的语义漂移
1348
+ */
1349
+ detectDrift(from, to) {
1350
+ const fromRuleMap = new Map(from.rules.map((r) => [r.id, r]));
1351
+ const toRuleMap = new Map(to.rules.map((r) => [r.id, r]));
1352
+ const addedRules = [];
1353
+ const removedRules = [];
1354
+ const modifiedRules = [];
1355
+ const decisionChanges = [];
1356
+ for (const [id, toRule] of toRuleMap) {
1357
+ const fromRule = fromRuleMap.get(id);
1358
+ if (!fromRule) {
1359
+ addedRules.push(id);
1360
+ } else if (this.ruleChanged(fromRule, toRule)) {
1361
+ modifiedRules.push(id);
1362
+ if (fromRule.decision !== toRule.decision) {
1363
+ decisionChanges.push({ ruleId: id, from: fromRule.decision, to: toRule.decision });
1364
+ }
1365
+ }
1366
+ }
1367
+ for (const id of fromRuleMap.keys()) {
1368
+ if (!toRuleMap.has(id)) {
1369
+ removedRules.push(id);
1370
+ }
1371
+ }
1372
+ const fromResources = new Set(from.rules.map((r) => r.resource));
1373
+ const toResources = new Set(to.rules.map((r) => r.resource));
1374
+ const newResources = [...toResources].filter((r) => !fromResources.has(r));
1375
+ const removedResources = [...fromResources].filter((r) => !toResources.has(r));
1376
+ const totalRules = Math.max(from.rules.length, to.rules.length, 1);
1377
+ const changeCount = addedRules.length + removedRules.length + modifiedRules.length;
1378
+ const decisionWeight = decisionChanges.length * 2;
1379
+ const driftScore = Math.min(1, (changeCount + decisionWeight) / totalRules);
1380
+ let severity = "none";
1381
+ if (driftScore >= this.config.criticalThreshold) severity = "critical";
1382
+ else if (driftScore >= this.config.highThreshold) severity = "high";
1383
+ else if (driftScore >= this.config.mediumThreshold) severity = "medium";
1384
+ else if (driftScore >= this.config.lowThreshold) severity = "low";
1385
+ const result = {
1386
+ fromVersion: from.version,
1387
+ toVersion: to.version,
1388
+ driftScore,
1389
+ ruleCountDelta: to.rules.length - from.rules.length,
1390
+ addedRules,
1391
+ removedRules,
1392
+ modifiedRules,
1393
+ decisionChanges,
1394
+ newResources,
1395
+ removedResources,
1396
+ severity,
1397
+ timestamp: Date.now()
1398
+ };
1399
+ this.history.push(result);
1400
+ if (severity !== "none" && this.config.onDriftDetected) {
1401
+ this.config.onDriftDetected(result);
1402
+ }
1403
+ if (this.config.onAudit) {
1404
+ this.config.onAudit({
1405
+ type: "drift_detected",
1406
+ details: { fromVersion: from.version, toVersion: to.version, driftScore, severity },
1407
+ timestamp: Date.now()
1408
+ });
1409
+ }
1410
+ return result;
1411
+ }
1412
+ /**
1413
+ * 获取漂移历史
1414
+ */
1415
+ getDriftHistory() {
1416
+ return [...this.history];
1417
+ }
1418
+ /**
1419
+ * 获取指纹
1420
+ */
1421
+ getFingerprint(version) {
1422
+ return this.fingerprints.get(version) ?? null;
1423
+ }
1424
+ /**
1425
+ * 获取漂移趋势
1426
+ */
1427
+ getDriftTrend() {
1428
+ return this.history.map((h) => ({
1429
+ version: h.toVersion,
1430
+ driftScore: h.driftScore,
1431
+ timestamp: h.timestamp
1432
+ }));
1433
+ }
1434
+ // ============================================
1435
+ // 私有方法
1436
+ // ============================================
1437
+ hashRules(rules) {
1438
+ const sorted = [...rules].sort((a, b) => a.id.localeCompare(b.id));
1439
+ const str = sorted.map((r) => `${r.id}:${r.action}:${r.resource}:${r.decision}:${r.priority}`).join("|");
1440
+ let hash = 0;
1441
+ for (let i = 0; i < str.length; i++) {
1442
+ const char = str.charCodeAt(i);
1443
+ hash = (hash << 5) - hash + char;
1444
+ hash = hash & hash;
1445
+ }
1446
+ return "fp_" + Math.abs(hash).toString(16).padStart(8, "0");
1447
+ }
1448
+ ruleChanged(a, b) {
1449
+ 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);
1450
+ }
1451
+ maxConditionDepth(rules) {
1452
+ let max = 0;
1453
+ for (const r of rules) {
1454
+ if (r.conditions) {
1455
+ max = Math.max(max, this.objectDepth(r.conditions));
1456
+ }
1457
+ }
1458
+ return max;
1459
+ }
1460
+ objectDepth(obj, depth = 0) {
1461
+ let max = depth;
1462
+ for (const val of Object.values(obj)) {
1463
+ if (val && typeof val === "object" && !Array.isArray(val)) {
1464
+ max = Math.max(max, this.objectDepth(val, depth + 1));
1465
+ }
1466
+ }
1467
+ return max;
1468
+ }
1469
+ };
1470
+ function createSemanticDriftDetector(config) {
1471
+ return new SemanticDriftDetectorEngine(config);
1472
+ }
1473
+
1474
+ // src/costGateEnhanced.ts
1475
+ var DEFAULT_CONFIG3 = {
1476
+ defaultBudgetUsd: 100,
1477
+ warningThreshold: 0.8,
1478
+ criticalThreshold: 0.95,
1479
+ humanReviewHourlyRateUsd: 50,
1480
+ toolCosts: [],
1481
+ onAudit: void 0,
1482
+ onBudgetExceeded: void 0
1483
+ };
1484
+ var CostGateEnhancedEngine = class {
1485
+ records = [];
1486
+ budgets = /* @__PURE__ */ new Map();
1487
+ // tenantId → budgetUsd
1488
+ config;
1489
+ toolCostMap = /* @__PURE__ */ new Map();
1490
+ constructor(config = {}) {
1491
+ this.config = { ...DEFAULT_CONFIG3, ...config };
1492
+ for (const tc of this.config.toolCosts) {
1493
+ this.toolCostMap.set(tc.toolName, tc);
1494
+ }
1495
+ }
1496
+ /**
1497
+ * E2: 记录成本并生成汇总
1498
+ */
1499
+ recordCost(record) {
1500
+ this.records.push(record);
1501
+ this.audit("cost_recorded", record.tenantId, { record });
1502
+ return this.checkBudget(record.tenantId, record.agentId, record.action);
1503
+ }
1504
+ /**
1505
+ * E2: 获取成本汇总(滑动窗口)
1506
+ */
1507
+ getCostSummary(tenantId, period) {
1508
+ const now = Date.now();
1509
+ const periodMs = {
1510
+ "1h": 36e5,
1511
+ "24h": 864e5,
1512
+ "7d": 6048e5,
1513
+ "30d": 2592e6
1514
+ };
1515
+ const startTime = now - (periodMs[period] || 864e5);
1516
+ const filtered = this.records.filter((r) => r.tenantId === tenantId && r.timestamp >= startTime);
1517
+ const byCategory = {
1518
+ llm_inference: 0,
1519
+ tool_call: 0,
1520
+ human_review: 0,
1521
+ storage: 0,
1522
+ network: 0,
1523
+ compute: 0,
1524
+ other: 0
1525
+ };
1526
+ const byAgent = {};
1527
+ const byTool = {};
1528
+ let totalCostUsd = 0;
1529
+ for (const r of filtered) {
1530
+ totalCostUsd += r.costUsd;
1531
+ byCategory[r.category] = (byCategory[r.category] || 0) + r.costUsd;
1532
+ byAgent[r.agentId] = (byAgent[r.agentId] || 0) + r.costUsd;
1533
+ if (r.toolName) {
1534
+ byTool[r.toolName] = (byTool[r.toolName] || 0) + r.costUsd;
1535
+ }
1536
+ }
1537
+ this.audit("summary_generated", tenantId, { period, totalCostUsd, recordCount: filtered.length });
1538
+ return {
1539
+ period,
1540
+ totalCostUsd,
1541
+ byCategory,
1542
+ byAgent,
1543
+ byTool,
1544
+ recordCount: filtered.length,
1545
+ avgCostPerAction: filtered.length > 0 ? totalCostUsd / filtered.length : 0,
1546
+ startTime,
1547
+ endTime: now
1548
+ };
1549
+ }
1550
+ /**
1551
+ * E7: getDailyCostStats — 按天统计
1552
+ */
1553
+ getDailyCostStats(tenantId, days = 30) {
1554
+ const now = Date.now();
1555
+ const startTime = now - days * 864e5;
1556
+ const filtered = this.records.filter((r) => r.tenantId === tenantId && r.timestamp >= startTime);
1557
+ const dailyMap = /* @__PURE__ */ new Map();
1558
+ for (const r of filtered) {
1559
+ const date = new Date(r.timestamp).toISOString().split("T")[0];
1560
+ if (!dailyMap.has(date)) {
1561
+ dailyMap.set(date, { records: [], agents: /* @__PURE__ */ new Set() });
1562
+ }
1563
+ const day = dailyMap.get(date);
1564
+ day.records.push(r);
1565
+ day.agents.add(r.agentId);
1566
+ }
1567
+ const budget = this.budgets.get(tenantId) ?? this.config.defaultBudgetUsd;
1568
+ const dailyBudget = budget / 30;
1569
+ return Array.from(dailyMap.entries()).map(([date, { records, agents }]) => {
1570
+ const byCategory = {
1571
+ llm_inference: 0,
1572
+ tool_call: 0,
1573
+ human_review: 0,
1574
+ storage: 0,
1575
+ network: 0,
1576
+ compute: 0,
1577
+ other: 0
1578
+ };
1579
+ let totalCostUsd = 0;
1580
+ for (const r of records) {
1581
+ totalCostUsd += r.costUsd;
1582
+ byCategory[r.category] = (byCategory[r.category] || 0) + r.costUsd;
1583
+ }
1584
+ return {
1585
+ date,
1586
+ totalCostUsd,
1587
+ byCategory,
1588
+ actionCount: records.length,
1589
+ uniqueAgents: agents.size,
1590
+ budgetUtilization: dailyBudget > 0 ? totalCostUsd / dailyBudget : 0
1591
+ };
1592
+ }).sort((a, b) => a.date.localeCompare(b.date));
1593
+ }
1594
+ /**
1595
+ * E9: 计算工具调用成本
1596
+ */
1597
+ calculateToolCost(toolName, tokenCount) {
1598
+ const config = this.toolCostMap.get(toolName);
1599
+ if (!config) return 1e-3;
1600
+ let cost = config.baseCostUsd + config.perCallCostUsd;
1601
+ if (tokenCount && config.perTokenCostUsd) {
1602
+ cost += tokenCount * config.perTokenCostUsd;
1603
+ }
1604
+ if (config.maxCostPerCallUsd) {
1605
+ cost = Math.min(cost, config.maxCostPerCallUsd);
1606
+ }
1607
+ return cost;
1608
+ }
1609
+ /**
1610
+ * E10: 计算人工审批成本
1611
+ */
1612
+ calculateHumanReviewCost(waitTimeMs, reviewTimeMs) {
1613
+ const totalTimeMs = waitTimeMs + reviewTimeMs;
1614
+ const hours = totalTimeMs / 36e5;
1615
+ const costUsd = hours * this.config.humanReviewHourlyRateUsd;
1616
+ return {
1617
+ reviewId: `review_${Date.now()}`,
1618
+ reviewerType: "human",
1619
+ waitTimeMs,
1620
+ reviewTimeMs,
1621
+ costUsd: Math.round(costUsd * 1e4) / 1e4,
1622
+ hourlyRateUsd: this.config.humanReviewHourlyRateUsd
1623
+ };
1624
+ }
1625
+ /**
1626
+ * 设置租户预算
1627
+ */
1628
+ setBudget(tenantId, budgetUsd) {
1629
+ this.budgets.set(tenantId, budgetUsd);
1630
+ }
1631
+ /**
1632
+ * 获取租户预算使用率
1633
+ */
1634
+ getBudgetUtilization(tenantId) {
1635
+ const budget = this.budgets.get(tenantId) ?? this.config.defaultBudgetUsd;
1636
+ const summary = this.getCostSummary(tenantId, "30d");
1637
+ return {
1638
+ used: summary.totalCostUsd,
1639
+ limit: budget,
1640
+ utilization: budget > 0 ? summary.totalCostUsd / budget : 0
1641
+ };
1642
+ }
1643
+ // ============================================
1644
+ // 私有方法
1645
+ // ============================================
1646
+ checkBudget(tenantId, agentId, action) {
1647
+ const budget = this.budgets.get(tenantId) ?? this.config.defaultBudgetUsd;
1648
+ const summary = this.getCostSummary(tenantId, "30d");
1649
+ const utilization = budget > 0 ? summary.totalCostUsd / budget : 0;
1650
+ if (utilization >= 1) {
1651
+ const event = {
1652
+ code: "BUDGET_EXCEEDED",
1653
+ tenantId,
1654
+ agentId,
1655
+ action,
1656
+ currentCostUsd: summary.totalCostUsd,
1657
+ budgetLimitUsd: budget,
1658
+ overage: summary.totalCostUsd - budget,
1659
+ period: "30d",
1660
+ timestamp: Date.now(),
1661
+ severity: "blocked"
1662
+ };
1663
+ this.audit("budget_exceeded", tenantId, { event });
1664
+ if (this.config.onBudgetExceeded) this.config.onBudgetExceeded(event);
1665
+ return event;
1666
+ }
1667
+ if (utilization >= this.config.criticalThreshold) {
1668
+ this.audit("budget_critical", tenantId, { utilization, budget });
1669
+ } else if (utilization >= this.config.warningThreshold) {
1670
+ this.audit("budget_warning", tenantId, { utilization, budget });
1671
+ }
1672
+ return null;
1673
+ }
1674
+ audit(type, tenantId, details) {
1675
+ if (this.config.onAudit) {
1676
+ this.config.onAudit({ type, tenantId, details, timestamp: Date.now() });
1677
+ }
1678
+ }
1679
+ };
1680
+ function createCostGateEnhanced(config) {
1681
+ return new CostGateEnhancedEngine(config);
1682
+ }
1683
+
1684
+ // src/budgetMultiLevel.ts
1685
+ var DEFAULT_ALERT_RULES = [
1686
+ { id: "warn_80", threshold: 0.8, severity: "warning", action: "notify", cooldownMs: 36e5 },
1687
+ { id: "crit_95", threshold: 0.95, severity: "critical", action: "throttle", cooldownMs: 18e5 },
1688
+ { id: "block_100", threshold: 1, severity: "critical", action: "block", cooldownMs: 3e5 }
1689
+ ];
1690
+ var DEFAULT_CONFIG4 = {
1691
+ defaultAlertRules: DEFAULT_ALERT_RULES,
1692
+ trendWindowDays: 30,
1693
+ onAlert: void 0,
1694
+ onAudit: void 0
1695
+ };
1696
+ var MultiLevelBudgetEngine = class {
1697
+ nodes = /* @__PURE__ */ new Map();
1698
+ spendHistory = [];
1699
+ config;
1700
+ constructor(config = {}) {
1701
+ this.config = { ...DEFAULT_CONFIG4, ...config };
1702
+ }
1703
+ /**
1704
+ * F6: 创建预算节点
1705
+ */
1706
+ createNode(node) {
1707
+ const budgetNode = {
1708
+ ...node,
1709
+ spentUsd: 0,
1710
+ children: [],
1711
+ alertRules: node.alertRules ?? [...this.config.defaultAlertRules]
1712
+ };
1713
+ this.nodes.set(budgetNode.id, budgetNode);
1714
+ if (node.parentId) {
1715
+ const parent = this.nodes.get(node.parentId);
1716
+ if (parent) {
1717
+ parent.children.push(budgetNode.id);
1718
+ }
1719
+ }
1720
+ return budgetNode;
1721
+ }
1722
+ /**
1723
+ * F6: 记录支出(向上冒泡到所有父级)
1724
+ */
1725
+ recordSpend(nodeId, amount) {
1726
+ const alerts = [];
1727
+ let current = this.nodes.get(nodeId);
1728
+ while (current) {
1729
+ current.spentUsd += amount;
1730
+ this.spendHistory.push({ nodeId: current.id, amount, timestamp: Date.now() });
1731
+ const nodeAlerts = this.checkAlerts(current);
1732
+ alerts.push(...nodeAlerts);
1733
+ current = current.parentId ? this.nodes.get(current.parentId) : void 0;
1734
+ }
1735
+ return alerts;
1736
+ }
1737
+ /**
1738
+ * F6: 获取节点预算状态(含子节点汇总)
1739
+ */
1740
+ getNodeStatus(nodeId) {
1741
+ const node = this.nodes.get(nodeId);
1742
+ if (!node) return null;
1743
+ const childrenSpent = this.getChildrenSpent(nodeId);
1744
+ const utilization = node.budgetUsd > 0 ? node.spentUsd / node.budgetUsd : 0;
1745
+ return {
1746
+ node,
1747
+ utilization,
1748
+ childrenSpent,
1749
+ remaining: Math.max(0, node.budgetUsd - node.spentUsd)
1750
+ };
1751
+ }
1752
+ /**
1753
+ * F7: 预测预算耗尽日期
1754
+ */
1755
+ predictExhaustion(nodeId) {
1756
+ const node = this.nodes.get(nodeId);
1757
+ if (!node || node.spentUsd === 0) return null;
1758
+ const remaining = node.budgetUsd - node.spentUsd;
1759
+ if (remaining <= 0) return (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
1760
+ const sevenDaysAgo = Date.now() - 7 * 864e5;
1761
+ const recentSpends = this.spendHistory.filter(
1762
+ (s) => s.nodeId === nodeId && s.timestamp >= sevenDaysAgo
1763
+ );
1764
+ const recentTotal = recentSpends.reduce((sum, s) => sum + s.amount, 0);
1765
+ const dailyRate = recentTotal / 7;
1766
+ if (dailyRate <= 0) return null;
1767
+ const daysRemaining = remaining / dailyRate;
1768
+ const exhaustionDate = new Date(Date.now() + daysRemaining * 864e5);
1769
+ return exhaustionDate.toISOString().split("T")[0];
1770
+ }
1771
+ /**
1772
+ * F8: 生成成本报告
1773
+ */
1774
+ generateReport(rootNodeId) {
1775
+ const nodes = rootNodeId ? this.getSubtree(rootNodeId) : Array.from(this.nodes.values());
1776
+ const byLevel = {
1777
+ organization: { budget: 0, spent: 0, count: 0 },
1778
+ team: { budget: 0, spent: 0, count: 0 },
1779
+ project: { budget: 0, spent: 0, count: 0 },
1780
+ agent: { budget: 0, spent: 0, count: 0 }
1781
+ };
1782
+ let totalBudget = 0;
1783
+ let totalSpent = 0;
1784
+ for (const n of nodes) {
1785
+ byLevel[n.level].budget += n.budgetUsd;
1786
+ byLevel[n.level].spent += n.spentUsd;
1787
+ byLevel[n.level].count++;
1788
+ if (n.children.length === 0) {
1789
+ totalBudget += n.budgetUsd;
1790
+ totalSpent += n.spentUsd;
1791
+ }
1792
+ }
1793
+ 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 }));
1794
+ const trend = this.generateTrend(rootNodeId);
1795
+ return {
1796
+ reportId: `report_${Date.now()}`,
1797
+ generatedAt: Date.now(),
1798
+ period: { start: Date.now() - this.config.trendWindowDays * 864e5, end: Date.now() },
1799
+ totalBudgetUsd: totalBudget,
1800
+ totalSpentUsd: totalSpent,
1801
+ utilization: totalBudget > 0 ? totalSpent / totalBudget : 0,
1802
+ byLevel,
1803
+ topSpenders,
1804
+ alerts: [],
1805
+ trend
1806
+ };
1807
+ }
1808
+ /**
1809
+ * 获取所有节点
1810
+ */
1811
+ listNodes(level) {
1812
+ const all = Array.from(this.nodes.values());
1813
+ return level ? all.filter((n) => n.level === level) : all;
1814
+ }
1815
+ // ============================================
1816
+ // 私有方法
1817
+ // ============================================
1818
+ checkAlerts(node) {
1819
+ const alerts = [];
1820
+ const utilization = node.budgetUsd > 0 ? node.spentUsd / node.budgetUsd : 0;
1821
+ for (const rule of node.alertRules) {
1822
+ if (utilization >= rule.threshold) {
1823
+ if (rule.lastTriggeredAt && Date.now() - rule.lastTriggeredAt < rule.cooldownMs) {
1824
+ continue;
1825
+ }
1826
+ rule.lastTriggeredAt = Date.now();
1827
+ const alert = {
1828
+ ruleId: rule.id,
1829
+ nodeId: node.id,
1830
+ nodeName: node.name,
1831
+ level: node.level,
1832
+ severity: rule.severity,
1833
+ action: rule.action,
1834
+ utilization,
1835
+ budgetUsd: node.budgetUsd,
1836
+ spentUsd: node.spentUsd,
1837
+ remainingUsd: Math.max(0, node.budgetUsd - node.spentUsd),
1838
+ predictedExhaustionDate: this.predictExhaustion(node.id) ?? void 0,
1839
+ timestamp: Date.now()
1840
+ };
1841
+ alerts.push(alert);
1842
+ if (this.config.onAlert) this.config.onAlert(alert);
1843
+ }
1844
+ }
1845
+ return alerts;
1846
+ }
1847
+ getChildrenSpent(nodeId) {
1848
+ const node = this.nodes.get(nodeId);
1849
+ if (!node) return 0;
1850
+ let total = 0;
1851
+ for (const childId of node.children) {
1852
+ const child = this.nodes.get(childId);
1853
+ if (child) {
1854
+ total += child.spentUsd;
1855
+ }
1856
+ }
1857
+ return total;
1858
+ }
1859
+ getSubtree(nodeId) {
1860
+ const result = [];
1861
+ const queue = [nodeId];
1862
+ while (queue.length > 0) {
1863
+ const id = queue.shift();
1864
+ const node = this.nodes.get(id);
1865
+ if (node) {
1866
+ result.push(node);
1867
+ queue.push(...node.children);
1868
+ }
1869
+ }
1870
+ return result;
1871
+ }
1872
+ generateTrend(rootNodeId) {
1873
+ const nodeIds = rootNodeId ? new Set(this.getSubtree(rootNodeId).map((n) => n.id)) : null;
1874
+ const startTime = Date.now() - this.config.trendWindowDays * 864e5;
1875
+ const filtered = this.spendHistory.filter((s) => {
1876
+ if (s.timestamp < startTime) return false;
1877
+ if (nodeIds && !nodeIds.has(s.nodeId)) return false;
1878
+ return true;
1879
+ });
1880
+ const dailyMap = /* @__PURE__ */ new Map();
1881
+ for (const s of filtered) {
1882
+ const date = new Date(s.timestamp).toISOString().split("T")[0];
1883
+ dailyMap.set(date, (dailyMap.get(date) ?? 0) + s.amount);
1884
+ }
1885
+ return Array.from(dailyMap.entries()).map(([date, spent]) => ({ date, spent })).sort((a, b) => a.date.localeCompare(b.date));
1886
+ }
1887
+ };
1888
+ function createMultiLevelBudget(config) {
1889
+ return new MultiLevelBudgetEngine(config);
1890
+ }
1891
+
1892
+ // src/evolutionChannel.ts
1893
+ var DEFAULT_CONFIG5 = {
1894
+ maxVersions: 50,
1895
+ canaryMinDurationMs: 36e5,
1896
+ // 1 小时
1897
+ autoPromoteThreshold: 0.95,
1898
+ onAudit: void 0
1899
+ };
1900
+ var EvolutionChannelEngine = class {
1901
+ versions = /* @__PURE__ */ new Map();
1902
+ activeVersionId = null;
1903
+ canaryVersionId = null;
1904
+ abTests = /* @__PURE__ */ new Map();
1905
+ config;
1906
+ constructor(config = {}) {
1907
+ this.config = { ...DEFAULT_CONFIG5, ...config };
1908
+ }
1909
+ /**
1910
+ * 发布新策略版本
1911
+ */
1912
+ publish(version) {
1913
+ if (this.versions.size >= this.config.maxVersions) {
1914
+ this.cleanupOldVersions();
1915
+ }
1916
+ version.status = "draft";
1917
+ version.createdAt = Date.now();
1918
+ this.versions.set(version.id, version);
1919
+ this.audit("publish", version.id, version.version, version.createdBy);
1920
+ return version;
1921
+ }
1922
+ /**
1923
+ * 启动灰度发布
1924
+ */
1925
+ startCanary(versionId, percent, actor) {
1926
+ const version = this.versions.get(versionId);
1927
+ if (!version || version.status !== "draft") return false;
1928
+ if (percent < 1 || percent > 99) return false;
1929
+ version.status = "canary";
1930
+ version.canaryPercent = percent;
1931
+ this.canaryVersionId = versionId;
1932
+ this.audit("canary_start", versionId, version.version, actor, { percent });
1933
+ return true;
1934
+ }
1935
+ /**
1936
+ * 灰度晋升为正式版本
1937
+ */
1938
+ promoteCanary(actor) {
1939
+ if (!this.canaryVersionId) return false;
1940
+ const canary = this.versions.get(this.canaryVersionId);
1941
+ if (!canary || canary.status !== "canary") return false;
1942
+ const elapsed = Date.now() - canary.createdAt;
1943
+ if (elapsed < this.config.canaryMinDurationMs) return false;
1944
+ if (this.activeVersionId) {
1945
+ const old = this.versions.get(this.activeVersionId);
1946
+ if (old) old.status = "deprecated";
1947
+ }
1948
+ canary.status = "active";
1949
+ canary.canaryPercent = 100;
1950
+ this.activeVersionId = this.canaryVersionId;
1951
+ this.canaryVersionId = null;
1952
+ this.audit("canary_promote", canary.id, canary.version, actor);
1953
+ return true;
1954
+ }
1955
+ /**
1956
+ * 灰度回滚
1957
+ */
1958
+ rollbackCanary(actor) {
1959
+ if (!this.canaryVersionId) return false;
1960
+ const canary = this.versions.get(this.canaryVersionId);
1961
+ if (!canary) return false;
1962
+ canary.status = "rollback";
1963
+ canary.canaryPercent = 0;
1964
+ this.canaryVersionId = null;
1965
+ this.audit("canary_rollback", canary.id, canary.version, actor);
1966
+ return true;
1967
+ }
1968
+ /**
1969
+ * 路由决策:根据灰度百分比选择策略版本
1970
+ */
1971
+ resolveVersion(requestHash) {
1972
+ if (this.canaryVersionId) {
1973
+ const canary = this.versions.get(this.canaryVersionId);
1974
+ if (canary && canary.status === "canary") {
1975
+ const hash = requestHash ?? Math.random() * 100;
1976
+ if (hash % 100 < canary.canaryPercent) {
1977
+ return canary;
1978
+ }
1979
+ }
1980
+ }
1981
+ if (this.activeVersionId) {
1982
+ return this.versions.get(this.activeVersionId) ?? null;
1983
+ }
1984
+ return null;
1985
+ }
1986
+ /**
1987
+ * 启动 A/B 测试
1988
+ */
1989
+ startABTest(testId, controlId, treatmentId, trafficSplit, actor) {
1990
+ const control = this.versions.get(controlId);
1991
+ const treatment = this.versions.get(treatmentId);
1992
+ if (!control || !treatment) return null;
1993
+ const test = {
1994
+ id: testId,
1995
+ controlVersionId: controlId,
1996
+ treatmentVersionId: treatmentId,
1997
+ trafficSplit: Math.max(1, Math.min(99, trafficSplit)),
1998
+ startedAt: Date.now(),
1999
+ status: "running",
2000
+ metrics: {
2001
+ controlDecisions: 0,
2002
+ treatmentDecisions: 0,
2003
+ controlAllowRate: 0,
2004
+ treatmentAllowRate: 0,
2005
+ controlAvgLatencyMs: 0,
2006
+ treatmentAvgLatencyMs: 0
2007
+ }
2008
+ };
2009
+ this.abTests.set(testId, test);
2010
+ this.audit("ab_test_start", testId, `${control.version} vs ${treatment.version}`, actor, { trafficSplit });
2011
+ return test;
2012
+ }
2013
+ /**
2014
+ * A/B 测试路由
2015
+ */
2016
+ resolveABTest(testId, requestHash) {
2017
+ const test = this.abTests.get(testId);
2018
+ if (!test || test.status !== "running") return null;
2019
+ const hash = requestHash ?? Math.random() * 100;
2020
+ const isTreatment = hash % 100 < test.trafficSplit;
2021
+ const versionId = isTreatment ? test.treatmentVersionId : test.controlVersionId;
2022
+ const version = this.versions.get(versionId);
2023
+ if (!version) return null;
2024
+ return { version, group: isTreatment ? "treatment" : "control" };
2025
+ }
2026
+ /**
2027
+ * 结束 A/B 测试
2028
+ */
2029
+ endABTest(testId, actor) {
2030
+ const test = this.abTests.get(testId);
2031
+ if (!test) return null;
2032
+ test.status = "completed";
2033
+ this.audit("ab_test_end", testId, "", actor, { metrics: test.metrics });
2034
+ return test;
2035
+ }
2036
+ /**
2037
+ * 获取所有版本
2038
+ */
2039
+ listVersions() {
2040
+ return Array.from(this.versions.values()).sort((a, b) => b.createdAt - a.createdAt);
2041
+ }
2042
+ /**
2043
+ * 获取当前 active 版本
2044
+ */
2045
+ getActiveVersion() {
2046
+ return this.activeVersionId ? this.versions.get(this.activeVersionId) ?? null : null;
2047
+ }
2048
+ // ============================================
2049
+ // 私有方法
2050
+ // ============================================
2051
+ cleanupOldVersions() {
2052
+ const deprecated = Array.from(this.versions.values()).filter((v) => v.status === "deprecated" || v.status === "rollback").sort((a, b) => a.createdAt - b.createdAt);
2053
+ if (deprecated.length > 0) {
2054
+ this.versions.delete(deprecated[0].id);
2055
+ }
2056
+ }
2057
+ audit(type, policyId, version, actor, details) {
2058
+ if (this.config.onAudit) {
2059
+ this.config.onAudit({ type, policyId, version, timestamp: Date.now(), actor, details });
2060
+ }
2061
+ }
2062
+ };
2063
+ function createEvolutionChannel(config) {
2064
+ return new EvolutionChannelEngine(config);
2065
+ }
2066
+
2067
+ // src/twoPhaseRouter.ts
2068
+ var DEFAULT_HARD_RULES = [
2069
+ {
2070
+ id: "HR-001",
2071
+ name: "high_risk_requires_powerful",
2072
+ condition: (req, candidate) => (req.riskLevel === "critical" || req.riskLevel === "high") && candidate.tier === "cheap",
2073
+ reasonCode: "RISK_TIER_MISMATCH",
2074
+ reasonTemplate: "High/critical risk tasks cannot use cheap tier models",
2075
+ enabled: true
2076
+ },
2077
+ {
2078
+ id: "HR-002",
2079
+ name: "critical_requires_powerful_only",
2080
+ condition: (req, candidate) => req.riskLevel === "critical" && candidate.tier !== "powerful",
2081
+ reasonCode: "RISK_TIER_MISMATCH",
2082
+ reasonTemplate: "Critical risk tasks require powerful tier models only",
2083
+ enabled: true
2084
+ },
2085
+ {
2086
+ id: "HR-003",
2087
+ name: "budget_hard_cap",
2088
+ condition: (req, candidate) => {
2089
+ if (!req.maxCostUsd) return false;
2090
+ const estimatedCost = req.estimatedTokens / 1e3 * candidate.costPer1kTokens;
2091
+ return estimatedCost > req.maxCostUsd;
2092
+ },
2093
+ reasonCode: "COST_EXCEEDS_BUDGET",
2094
+ reasonTemplate: "Estimated cost exceeds hard budget cap",
2095
+ enabled: true
2096
+ }
2097
+ ];
2098
+ var DEFAULT_SCORING_WEIGHTS = {
2099
+ cost: 0.25,
2100
+ latency: 0.2,
2101
+ capability: 0.25,
2102
+ weight: 0.15,
2103
+ tierMatch: 0.15
2104
+ };
2105
+ var TwoPhaseRouter = class {
2106
+ config;
2107
+ constructor(config) {
2108
+ this.config = {
2109
+ ...config,
2110
+ hardRules: config.hardRules.length > 0 ? config.hardRules : DEFAULT_HARD_RULES,
2111
+ scoringWeights: config.scoringWeights ?? DEFAULT_SCORING_WEIGHTS
2112
+ };
2113
+ }
2114
+ /**
2115
+ * Phase 1: Eligibility — 硬性规则过滤
2116
+ */
2117
+ evaluateEligibility(request) {
2118
+ return this.config.models.map((candidate) => {
2119
+ if (!candidate.enabled) {
2120
+ return {
2121
+ candidateId: candidate.id,
2122
+ eligible: false,
2123
+ reasonCode: "DISABLED",
2124
+ reasonDetail: `Model ${candidate.name} is disabled`
2125
+ };
2126
+ }
2127
+ const missingCaps = request.requiredCapabilities.filter(
2128
+ (cap) => !candidate.capabilities.includes(cap)
2129
+ );
2130
+ if (missingCaps.length > 0) {
2131
+ return {
2132
+ candidateId: candidate.id,
2133
+ eligible: false,
2134
+ reasonCode: "CAPABILITY_MISSING",
2135
+ reasonDetail: `Missing capabilities: ${missingCaps.join(", ")}`
2136
+ };
2137
+ }
2138
+ if (request.estimatedTokens > candidate.maxContextTokens) {
2139
+ return {
2140
+ candidateId: candidate.id,
2141
+ eligible: false,
2142
+ reasonCode: "CONTEXT_TOO_LARGE",
2143
+ reasonDetail: `Estimated ${request.estimatedTokens} tokens exceeds max ${candidate.maxContextTokens}`
2144
+ };
2145
+ }
2146
+ if (request.maxLatencyMs && candidate.avgLatencyMs > request.maxLatencyMs) {
2147
+ return {
2148
+ candidateId: candidate.id,
2149
+ eligible: false,
2150
+ reasonCode: "LATENCY_EXCEEDS_LIMIT",
2151
+ reasonDetail: `Avg latency ${candidate.avgLatencyMs}ms exceeds limit ${request.maxLatencyMs}ms`
2152
+ };
2153
+ }
2154
+ for (const rule of this.config.hardRules) {
2155
+ if (!rule.enabled) continue;
2156
+ if (rule.condition(request, candidate)) {
2157
+ return {
2158
+ candidateId: candidate.id,
2159
+ eligible: false,
2160
+ reasonCode: rule.reasonCode,
2161
+ reasonDetail: rule.reasonTemplate
2162
+ };
2163
+ }
2164
+ }
2165
+ return {
2166
+ candidateId: candidate.id,
2167
+ eligible: true,
2168
+ reasonCode: "ELIGIBLE",
2169
+ reasonDetail: "Passed all eligibility checks"
2170
+ };
2171
+ });
2172
+ }
2173
+ /**
2174
+ * Phase 2: Scoring — 软性指标加权评分
2175
+ */
2176
+ evaluateScoring(request, eligibleIds) {
2177
+ const eligible = this.config.models.filter((m) => eligibleIds.has(m.id));
2178
+ if (eligible.length === 0) return [];
2179
+ const w = this.config.scoringWeights;
2180
+ const maxCost = Math.max(...eligible.map((m) => m.costPer1kTokens), 1e-3);
2181
+ const maxLatency = Math.max(...eligible.map((m) => m.avgLatencyMs), 1);
2182
+ return eligible.map((candidate) => {
2183
+ const costScore = 100 * (1 - candidate.costPer1kTokens / maxCost);
2184
+ const latencyScore = 100 * (1 - candidate.avgLatencyMs / maxLatency);
2185
+ const matchedCaps = request.requiredCapabilities.filter(
2186
+ (cap) => candidate.capabilities.includes(cap)
2187
+ ).length;
2188
+ const capabilityScore = request.requiredCapabilities.length > 0 ? 100 * (matchedCaps / request.requiredCapabilities.length) : 50;
2189
+ const weightScore = candidate.weight;
2190
+ let tierMatchScore = 50;
2191
+ if (request.preferredTier) {
2192
+ if (candidate.tier === request.preferredTier) tierMatchScore = 100;
2193
+ else {
2194
+ const tierOrder = ["cheap", "balanced", "powerful"];
2195
+ const diff = Math.abs(
2196
+ tierOrder.indexOf(candidate.tier) - tierOrder.indexOf(request.preferredTier)
2197
+ );
2198
+ tierMatchScore = Math.max(0, 100 - diff * 40);
2199
+ }
2200
+ }
2201
+ const score = costScore * w.cost + latencyScore * w.latency + capabilityScore * w.capability + weightScore * w.weight + tierMatchScore * w.tierMatch;
2202
+ return {
2203
+ candidateId: candidate.id,
2204
+ score: Math.round(score * 100) / 100,
2205
+ breakdown: {
2206
+ costScore: Math.round(costScore * 100) / 100,
2207
+ latencyScore: Math.round(latencyScore * 100) / 100,
2208
+ capabilityScore: Math.round(capabilityScore * 100) / 100,
2209
+ weightScore: Math.round(weightScore * 100) / 100,
2210
+ tierMatchScore: Math.round(tierMatchScore * 100) / 100
2211
+ }
2212
+ };
2213
+ });
2214
+ }
2215
+ /**
2216
+ * Main routing decision
2217
+ */
2218
+ async route(request) {
2219
+ const startTime = Date.now();
2220
+ const phase1Results = this.evaluateEligibility(request);
2221
+ const eligibleIds = new Set(
2222
+ phase1Results.filter((r) => r.eligible).map((r) => r.candidateId)
2223
+ );
2224
+ const phase2Results = this.evaluateScoring(request, eligibleIds);
2225
+ phase2Results.sort((a, b) => b.score - a.score);
2226
+ let selectedModelId;
2227
+ let fallbackUsed = false;
2228
+ const reasonChain = [];
2229
+ if (phase2Results.length > 0) {
2230
+ selectedModelId = phase2Results[0].candidateId;
2231
+ reasonChain.push(
2232
+ `Phase 1: ${eligibleIds.size}/${this.config.models.length} candidates eligible`
2233
+ );
2234
+ reasonChain.push(
2235
+ `Phase 2: Top scorer = ${selectedModelId} (score: ${phase2Results[0].score})`
2236
+ );
2237
+ const rejected = phase1Results.filter((r) => !r.eligible);
2238
+ if (rejected.length > 0) {
2239
+ reasonChain.push(
2240
+ `Rejected: ${rejected.map((r) => `${r.candidateId}(${r.reasonCode})`).join(", ")}`
2241
+ );
2242
+ }
2243
+ } else if (this.config.fallbackModelId) {
2244
+ selectedModelId = this.config.fallbackModelId;
2245
+ fallbackUsed = true;
2246
+ reasonChain.push("Phase 1: No eligible candidates");
2247
+ reasonChain.push(`Fallback: Using ${selectedModelId}`);
2248
+ } else {
2249
+ const leastBad = this.config.models.find((m) => m.enabled);
2250
+ selectedModelId = leastBad?.id ?? this.config.models[0]?.id ?? "unknown";
2251
+ fallbackUsed = true;
2252
+ reasonChain.push("Phase 1: No eligible candidates, no fallback configured");
2253
+ reasonChain.push(`Emergency: Using ${selectedModelId}`);
2254
+ }
2255
+ const selectedModel = this.config.models.find((m) => m.id === selectedModelId);
2256
+ const decisionTimeMs = Date.now() - startTime;
2257
+ const decision = {
2258
+ selectedModelId,
2259
+ selectedModelName: selectedModel?.name ?? "unknown",
2260
+ tier: selectedModel?.tier ?? this.config.defaultTier,
2261
+ phase1Results,
2262
+ phase2Results,
2263
+ reasonChain,
2264
+ totalCandidates: this.config.models.length,
2265
+ eligibleCandidates: eligibleIds.size,
2266
+ decisionTimeMs,
2267
+ fallbackUsed
2268
+ };
2269
+ if (this.config.onDecision) {
2270
+ try {
2271
+ await this.config.onDecision(decision);
2272
+ } catch {
2273
+ }
2274
+ }
2275
+ if (this.config.onAudit) {
2276
+ try {
2277
+ await this.config.onAudit({
2278
+ type: "routing_decision",
2279
+ data: {
2280
+ selectedModelId,
2281
+ tier: decision.tier,
2282
+ eligibleCount: eligibleIds.size,
2283
+ totalCount: this.config.models.length,
2284
+ fallbackUsed,
2285
+ decisionTimeMs,
2286
+ taskType: request.taskType,
2287
+ riskLevel: request.riskLevel
2288
+ }
2289
+ });
2290
+ } catch {
2291
+ }
2292
+ }
2293
+ return decision;
2294
+ }
2295
+ /**
2296
+ * Get models by tier
2297
+ */
2298
+ getModelsByTier(tier) {
2299
+ return this.config.models.filter((m) => m.tier === tier && m.enabled);
2300
+ }
2301
+ /**
2302
+ * Update model status
2303
+ */
2304
+ updateModel(modelId, updates) {
2305
+ const idx = this.config.models.findIndex((m) => m.id === modelId);
2306
+ if (idx === -1) return false;
2307
+ this.config.models[idx] = { ...this.config.models[idx], ...updates };
2308
+ return true;
2309
+ }
2310
+ /**
2311
+ * Add a new hard rule
2312
+ */
2313
+ addHardRule(rule) {
2314
+ this.config.hardRules.push(rule);
2315
+ }
2316
+ /**
2317
+ * Get routing explanation for a specific request (dry run)
2318
+ */
2319
+ async explain(request) {
2320
+ const decision = await this.route(request);
2321
+ const lines = [
2322
+ `=== SOVR Routing Explanation ===`,
2323
+ `Task: ${request.taskType} | Risk: ${request.riskLevel}`,
2324
+ `Required Capabilities: ${request.requiredCapabilities.join(", ") || "none"}`,
2325
+ `Estimated Tokens: ${request.estimatedTokens}`,
2326
+ ``,
2327
+ `--- Phase 1: Eligibility ---`
2328
+ ];
2329
+ for (const r of decision.phase1Results) {
2330
+ const model = this.config.models.find((m) => m.id === r.candidateId);
2331
+ lines.push(
2332
+ ` ${r.eligible ? "\u2705" : "\u274C"} ${model?.name ?? r.candidateId} [${r.reasonCode}] ${r.reasonDetail}`
2333
+ );
2334
+ }
2335
+ lines.push("", `--- Phase 2: Scoring ---`);
2336
+ for (const r of decision.phase2Results) {
2337
+ const model = this.config.models.find((m) => m.id === r.candidateId);
2338
+ lines.push(
2339
+ ` ${model?.name ?? r.candidateId}: ${r.score} (cost=${r.breakdown.costScore} lat=${r.breakdown.latencyScore} cap=${r.breakdown.capabilityScore})`
2340
+ );
2341
+ }
2342
+ lines.push(
2343
+ "",
2344
+ `--- Decision ---`,
2345
+ `Selected: ${decision.selectedModelName} (${decision.tier})`,
2346
+ `Fallback: ${decision.fallbackUsed ? "YES" : "NO"}`,
2347
+ `Time: ${decision.decisionTimeMs}ms`
2348
+ );
2349
+ return { decision, explanation: lines.join("\n") };
2350
+ }
2351
+ };
2352
+
2353
+ // src/timeSeriesAggregator.ts
2354
+ var DEFAULT_TSA_CONFIG = {
2355
+ windowSizeMs: 6e4,
2356
+ // 1 minute
2357
+ windowType: "tumbling",
2358
+ maxWindows: 60,
2359
+ // Keep 1 hour of 1-min windows
2360
+ maxValuesPerWindow: 1e4
2361
+ };
2362
+ function percentile(sorted, p) {
2363
+ if (sorted.length === 0) return 0;
2364
+ if (sorted.length === 1) return sorted[0];
2365
+ const idx = p / 100 * (sorted.length - 1);
2366
+ const lower = Math.floor(idx);
2367
+ const upper = Math.ceil(idx);
2368
+ if (lower === upper) return sorted[lower];
2369
+ return sorted[lower] + (sorted[upper] - sorted[lower]) * (idx - lower);
2370
+ }
2371
+ var TimeSeriesAggregator = class {
2372
+ windows = /* @__PURE__ */ new Map();
2373
+ closedResults = [];
2374
+ config;
2375
+ totalDedups = 0;
2376
+ constructor(config) {
2377
+ this.config = { ...DEFAULT_TSA_CONFIG, ...config };
2378
+ }
2379
+ /**
2380
+ * Ingest a data point (idempotent — duplicates are rejected)
2381
+ */
2382
+ async ingest(point) {
2383
+ const windowId = this.getWindowId(point.timestamp);
2384
+ let window = this.windows.get(windowId);
2385
+ if (!window) {
2386
+ window = this.createWindow(windowId, point.timestamp);
2387
+ this.windows.set(windowId, window);
2388
+ this.evictOldWindows();
2389
+ }
2390
+ if (window.seenIds.has(point.id)) {
2391
+ this.totalDedups++;
2392
+ return { accepted: false, windowId, duplicate: true };
2393
+ }
2394
+ window.seenIds.add(point.id);
2395
+ window.count++;
2396
+ window.sum += point.value;
2397
+ window.min = Math.min(window.min, point.value);
2398
+ window.max = Math.max(window.max, point.value);
2399
+ if (window.values.length < this.config.maxValuesPerWindow) {
2400
+ window.values.push(point.value);
2401
+ }
2402
+ return { accepted: true, windowId, duplicate: false };
2403
+ }
2404
+ /**
2405
+ * Ingest multiple points (batch)
2406
+ */
2407
+ async ingestBatch(points) {
2408
+ let accepted = 0;
2409
+ let duplicates = 0;
2410
+ let errors = 0;
2411
+ for (const point of points) {
2412
+ try {
2413
+ const result = await this.ingest(point);
2414
+ if (result.accepted) accepted++;
2415
+ if (result.duplicate) duplicates++;
2416
+ } catch {
2417
+ errors++;
2418
+ }
2419
+ }
2420
+ return { accepted, duplicates, errors };
2421
+ }
2422
+ /**
2423
+ * Get aggregation result for a specific window
2424
+ */
2425
+ getWindowResult(windowId) {
2426
+ const window = this.windows.get(windowId);
2427
+ if (!window) {
2428
+ return this.closedResults.find((r) => r.windowId === windowId) ?? null;
2429
+ }
2430
+ return this.computeResult(window);
2431
+ }
2432
+ /**
2433
+ * Get current (latest) window result
2434
+ */
2435
+ getCurrentResult() {
2436
+ const now = Date.now();
2437
+ const windowId = this.getWindowId(now);
2438
+ return this.getWindowResult(windowId);
2439
+ }
2440
+ /**
2441
+ * Get results for a time range
2442
+ */
2443
+ getResultsInRange(startMs, endMs) {
2444
+ const results = [];
2445
+ for (const window of this.windows.values()) {
2446
+ if (window.startMs >= startMs && window.endMs <= endMs) {
2447
+ results.push(this.computeResult(window));
2448
+ }
2449
+ }
2450
+ for (const result of this.closedResults) {
2451
+ if (result.startMs >= startMs && result.endMs <= endMs) {
2452
+ if (!results.find((r) => r.windowId === result.windowId)) {
2453
+ results.push(result);
2454
+ }
2455
+ }
2456
+ }
2457
+ return results.sort((a, b) => a.startMs - b.startMs);
2458
+ }
2459
+ /**
2460
+ * Close current window and emit result
2461
+ */
2462
+ async closeWindow(windowId) {
2463
+ const window = this.windows.get(windowId);
2464
+ if (!window) return null;
2465
+ const result = this.computeResult(window);
2466
+ this.closedResults.push(result);
2467
+ this.windows.delete(windowId);
2468
+ if (this.closedResults.length > this.config.maxWindows * 2) {
2469
+ this.closedResults = this.closedResults.slice(-this.config.maxWindows);
2470
+ }
2471
+ if (this.config.onWindowClosed) {
2472
+ try {
2473
+ await this.config.onWindowClosed(result);
2474
+ } catch {
2475
+ }
2476
+ }
2477
+ if (this.config.onAudit) {
2478
+ try {
2479
+ await this.config.onAudit({
2480
+ type: "window_closed",
2481
+ data: {
2482
+ windowId,
2483
+ count: result.metrics.count,
2484
+ avg: result.metrics.avg,
2485
+ p95: result.metrics.p95,
2486
+ dedupCount: result.dedupCount
2487
+ }
2488
+ });
2489
+ } catch {
2490
+ }
2491
+ }
2492
+ return result;
2493
+ }
2494
+ /**
2495
+ * Get overall stats
2496
+ */
2497
+ getStats() {
2498
+ let totalDataPoints = 0;
2499
+ for (const w of this.windows.values()) totalDataPoints += w.count;
2500
+ for (const r of this.closedResults) totalDataPoints += r.metrics.count;
2501
+ return {
2502
+ activeWindows: this.windows.size,
2503
+ closedWindows: this.closedResults.length,
2504
+ totalDedups: this.totalDedups,
2505
+ totalDataPoints
2506
+ };
2507
+ }
2508
+ /**
2509
+ * Reset all windows
2510
+ */
2511
+ reset() {
2512
+ this.windows.clear();
2513
+ this.closedResults = [];
2514
+ this.totalDedups = 0;
2515
+ }
2516
+ // ─── Internal ────────────────────────────────────────────────────
2517
+ getWindowId(timestamp) {
2518
+ const windowStart = Math.floor(timestamp / this.config.windowSizeMs) * this.config.windowSizeMs;
2519
+ return `w_${windowStart}`;
2520
+ }
2521
+ createWindow(windowId, timestamp) {
2522
+ const windowStart = Math.floor(timestamp / this.config.windowSizeMs) * this.config.windowSizeMs;
2523
+ return {
2524
+ windowId,
2525
+ windowType: this.config.windowType,
2526
+ startMs: windowStart,
2527
+ endMs: windowStart + this.config.windowSizeMs,
2528
+ count: 0,
2529
+ sum: 0,
2530
+ min: Infinity,
2531
+ max: -Infinity,
2532
+ values: [],
2533
+ seenIds: /* @__PURE__ */ new Set()
2534
+ };
2535
+ }
2536
+ computeResult(window) {
2537
+ const sorted = [...window.values].sort((a, b) => a - b);
2538
+ const durationSec = (window.endMs - window.startMs) / 1e3;
2539
+ return {
2540
+ windowId: window.windowId,
2541
+ windowType: window.windowType,
2542
+ startMs: window.startMs,
2543
+ endMs: window.endMs,
2544
+ metrics: {
2545
+ count: window.count,
2546
+ sum: window.sum,
2547
+ avg: window.count > 0 ? window.sum / window.count : 0,
2548
+ min: window.min === Infinity ? 0 : window.min,
2549
+ max: window.max === -Infinity ? 0 : window.max,
2550
+ p50: percentile(sorted, 50),
2551
+ p95: percentile(sorted, 95),
2552
+ p99: percentile(sorted, 99),
2553
+ rate: durationSec > 0 ? window.count / durationSec : 0
2554
+ },
2555
+ dedupCount: window.seenIds.size - window.count > 0 ? 0 : this.totalDedups
2556
+ };
2557
+ }
2558
+ evictOldWindows() {
2559
+ if (this.windows.size <= this.config.maxWindows) return;
2560
+ const sorted = Array.from(this.windows.entries()).sort((a, b) => a[1].startMs - b[1].startMs);
2561
+ while (sorted.length > this.config.maxWindows) {
2562
+ const [id, window] = sorted.shift();
2563
+ this.closedResults.push(this.computeResult(window));
2564
+ this.windows.delete(id);
2565
+ }
2566
+ }
2567
+ };
2568
+
2569
+ // src/valuationModel.ts
2570
+ var ValuationModel = class {
2571
+ config;
2572
+ constructor(config) {
2573
+ this.config = config ?? {};
2574
+ }
2575
+ /**
2576
+ * Calculate TAM/SAM/SOM
2577
+ */
2578
+ calculateMarketSize(input) {
2579
+ return {
2580
+ tam: input.totalMarketUsd,
2581
+ sam: input.totalMarketUsd * input.serviceablePercent,
2582
+ som: input.totalMarketUsd * input.serviceablePercent * input.obtainablePercent,
2583
+ year: input.year,
2584
+ growthRate: input.growthRate,
2585
+ assumptions: input.assumptions
2586
+ };
2587
+ }
2588
+ /**
2589
+ * Calculate Unit Economics
2590
+ */
2591
+ calculateUnitEconomics(input) {
2592
+ const netChurn = input.churnRate - input.expansionRate;
2593
+ const effectiveChurn = Math.max(netChurn, 1e-3);
2594
+ const ltv = input.arpu * input.grossMargin / effectiveChurn;
2595
+ const paybackMonths = input.cac / (input.arpu * input.grossMargin);
2596
+ return {
2597
+ arpu: input.arpu,
2598
+ cac: input.cac,
2599
+ ltv: Math.round(ltv * 100) / 100,
2600
+ ltvCacRatio: Math.round(ltv / input.cac * 100) / 100,
2601
+ paybackMonths: Math.round(paybackMonths * 10) / 10,
2602
+ grossMargin: input.grossMargin,
2603
+ churnRate: input.churnRate,
2604
+ expansionRate: input.expansionRate
2605
+ };
2606
+ }
2607
+ /**
2608
+ * DCF Valuation
2609
+ */
2610
+ calculateDCF(input) {
2611
+ const fcfs = [];
2612
+ const discountedFcfs = [];
2613
+ for (let i = 0; i < input.projectedRevenues.length; i++) {
2614
+ const revenue = input.projectedRevenues[i];
2615
+ const operatingIncome = revenue * input.operatingMargin;
2616
+ const afterTax = operatingIncome * (1 - input.taxRate);
2617
+ const capex = revenue * input.capexRatio;
2618
+ const fcf = afterTax - capex;
2619
+ fcfs.push(fcf);
2620
+ const discountFactor = Math.pow(1 + input.discountRate, i + 1);
2621
+ discountedFcfs.push(fcf / discountFactor);
2622
+ }
2623
+ const presentValue = discountedFcfs.reduce((sum, v) => sum + v, 0);
2624
+ const lastFcf = fcfs[fcfs.length - 1] ?? 0;
2625
+ const terminalFcf = lastFcf * (1 + input.terminalGrowthRate);
2626
+ const terminalValue = terminalFcf / (input.discountRate - input.terminalGrowthRate);
2627
+ const discountedTerminal = terminalValue / Math.pow(1 + input.discountRate, input.projectedRevenues.length);
2628
+ const enterpriseValue = presentValue + discountedTerminal;
2629
+ const lastRevenue = input.projectedRevenues[input.projectedRevenues.length - 1] ?? 1;
2630
+ const impliedMultiple = enterpriseValue / lastRevenue;
2631
+ return {
2632
+ presentValue: Math.round(presentValue),
2633
+ terminalValue: Math.round(discountedTerminal),
2634
+ enterpriseValue: Math.round(enterpriseValue),
2635
+ freeCashFlows: fcfs.map((v) => Math.round(v)),
2636
+ discountedCashFlows: discountedFcfs.map((v) => Math.round(v)),
2637
+ impliedMultiple: Math.round(impliedMultiple * 10) / 10
2638
+ };
2639
+ }
2640
+ /**
2641
+ * Comparable Company Valuation
2642
+ */
2643
+ calculateComparable(input) {
2644
+ const revMultiples = input.comparables.map((c) => c.evRevenue);
2645
+ const ebitdaMultiples = input.comparables.map((c) => c.evEbitda);
2646
+ const userValues = input.comparables.map((c) => c.evUser);
2647
+ const medianRevMultiple = this.median(revMultiples);
2648
+ const medianEbitdaMultiple = this.median(ebitdaMultiples);
2649
+ const medianUserValue = this.median(userValues);
2650
+ const revenueVal = input.revenue * medianRevMultiple;
2651
+ const ebitdaVal = input.ebitda * medianEbitdaMultiple;
2652
+ const userVal = input.users * medianUserValue;
2653
+ const avgCompGrowth = input.comparables.reduce((s, c) => s + c.growthRate, 0) / input.comparables.length;
2654
+ const growthPremium = input.growthRate / (avgCompGrowth || 0.1);
2655
+ const growthAdjusted = revenueVal * Math.min(growthPremium, 3);
2656
+ return {
2657
+ revenueMultipleValuation: Math.round(revenueVal),
2658
+ ebitdaMultipleValuation: Math.round(ebitdaVal),
2659
+ perUserValuation: Math.round(userVal),
2660
+ averageValuation: Math.round((revenueVal + ebitdaVal + userVal) / 3),
2661
+ medianMultiple: medianRevMultiple,
2662
+ growthAdjustedValuation: Math.round(growthAdjusted)
2663
+ };
2664
+ }
2665
+ /**
2666
+ * Network Effect Valuation (Metcalfe's Law)
2667
+ */
2668
+ calculateNetworkEffect(input) {
2669
+ const currentValue = Math.pow(input.currentUsers, input.metcalfeExponent) * input.valuePerConnection * input.networkDensity;
2670
+ const projectedValues = input.projectedUsers.map(
2671
+ (users) => Math.pow(users, input.metcalfeExponent) * input.valuePerConnection * input.networkDensity
2672
+ );
2673
+ const metcalfeValue = Math.pow(input.currentUsers, 2) * input.valuePerConnection;
2674
+ const adjustedValue = metcalfeValue * input.networkDensity;
2675
+ return {
2676
+ currentNetworkValue: Math.round(currentValue),
2677
+ projectedValues: projectedValues.map((v) => Math.round(v)),
2678
+ metcalfeValue: Math.round(metcalfeValue),
2679
+ adjustedValue: Math.round(adjustedValue)
2680
+ };
2681
+ }
2682
+ /**
2683
+ * Sensitivity Analysis
2684
+ */
2685
+ runSensitivity(baseInput, variables) {
2686
+ const baseResult = this.calculateDCF(baseInput);
2687
+ const baseCase = baseResult.enterpriseValue;
2688
+ const scenarios = [];
2689
+ const tornado = [];
2690
+ for (const v of variables) {
2691
+ const lowInput = { ...baseInput, [v.field]: v.low };
2692
+ const lowResult = this.calculateDCF(lowInput);
2693
+ const highInput = { ...baseInput, [v.field]: v.high };
2694
+ const highResult = this.calculateDCF(highInput);
2695
+ scenarios.push({
2696
+ name: `${v.name} Low`,
2697
+ value: lowResult.enterpriseValue,
2698
+ delta: (lowResult.enterpriseValue - baseCase) / baseCase * 100,
2699
+ variables: { [v.name]: v.low }
2700
+ });
2701
+ scenarios.push({
2702
+ name: `${v.name} High`,
2703
+ value: highResult.enterpriseValue,
2704
+ delta: (highResult.enterpriseValue - baseCase) / baseCase * 100,
2705
+ variables: { [v.name]: v.high }
2706
+ });
2707
+ tornado.push({
2708
+ variable: v.name,
2709
+ lowValue: lowResult.enterpriseValue,
2710
+ highValue: highResult.enterpriseValue,
2711
+ range: Math.abs(highResult.enterpriseValue - lowResult.enterpriseValue)
2712
+ });
2713
+ }
2714
+ tornado.sort((a, b) => b.range - a.range);
2715
+ return { baseCase, scenarios, tornado };
2716
+ }
2717
+ // ─── Helpers ─────────────────────────────────────────────────────
2718
+ median(values) {
2719
+ if (values.length === 0) return 0;
2720
+ const sorted = [...values].sort((a, b) => a - b);
2721
+ const mid = Math.floor(sorted.length / 2);
2722
+ return sorted.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
2723
+ }
2724
+ };
2725
+
2726
+ // src/governanceEnhancer.ts
2727
+ var DEFAULT_GE_CONFIG = {
2728
+ circuitBreakerThreshold: 5,
2729
+ circuitBreakerTimeoutMs: 3e4,
2730
+ halfOpenSuccessThreshold: 3,
2731
+ degradationChain: [
2732
+ {
2733
+ id: "full",
2734
+ name: "Full Capability",
2735
+ order: 4,
2736
+ capabilities: ["all"],
2737
+ restrictions: []
2738
+ },
2739
+ {
2740
+ id: "reduced",
2741
+ name: "Reduced Capability",
2742
+ order: 3,
2743
+ capabilities: ["read", "compute", "cache"],
2744
+ restrictions: ["write", "external_api"]
2745
+ },
2746
+ {
2747
+ id: "minimal",
2748
+ name: "Minimal Capability",
2749
+ order: 2,
2750
+ capabilities: ["read", "cache"],
2751
+ restrictions: ["write", "compute", "external_api"]
2752
+ },
2753
+ {
2754
+ id: "readonly",
2755
+ name: "Read-Only Mode",
2756
+ order: 1,
2757
+ capabilities: ["read"],
2758
+ restrictions: ["write", "compute", "external_api", "cache"]
2759
+ }
2760
+ ],
2761
+ maxPolicyVersions: 10
2762
+ };
2763
+ function simpleHash2(input) {
2764
+ let hash = 0;
2765
+ for (let i = 0; i < input.length; i++) {
2766
+ hash = (hash << 5) - hash + input.charCodeAt(i);
2767
+ hash = hash & hash;
2768
+ }
2769
+ return Math.abs(hash).toString(16).padStart(8, "0");
2770
+ }
2771
+ var GovernanceEnhancer = class {
2772
+ currentPolicy = null;
2773
+ policyHistory = [];
2774
+ circuitBreakers = /* @__PURE__ */ new Map();
2775
+ currentDegradationLevel = "full";
2776
+ config;
2777
+ constructor(config) {
2778
+ this.config = { ...DEFAULT_GE_CONFIG, ...config };
2779
+ }
2780
+ // ─── Policy Hot-Reload ───────────────────────────────────────────
2781
+ /**
2782
+ * Load a new policy version (hot-reload)
2783
+ */
2784
+ async loadPolicy(version, rules) {
2785
+ const hash = simpleHash2(JSON.stringify(rules));
2786
+ const oldVersion = this.currentPolicy?.version;
2787
+ const newPolicy = {
2788
+ version,
2789
+ rules: rules.sort((a, b) => b.priority - a.priority),
2790
+ activatedAt: Date.now(),
2791
+ hash
2792
+ };
2793
+ if (this.currentPolicy) {
2794
+ this.policyHistory.push(this.currentPolicy);
2795
+ if (this.policyHistory.length > this.config.maxPolicyVersions) {
2796
+ this.policyHistory = this.policyHistory.slice(-this.config.maxPolicyVersions);
2797
+ }
2798
+ }
2799
+ this.currentPolicy = newPolicy;
2800
+ if (this.config.onPolicyChange && oldVersion) {
2801
+ try {
2802
+ await this.config.onPolicyChange(oldVersion, version);
2803
+ } catch {
2804
+ }
2805
+ }
2806
+ if (this.config.onAudit) {
2807
+ try {
2808
+ await this.config.onAudit({
2809
+ type: "policy_loaded",
2810
+ data: { version, ruleCount: rules.length, hash, previousVersion: oldVersion }
2811
+ });
2812
+ } catch {
2813
+ }
2814
+ }
2815
+ return { success: true, previousVersion: oldVersion, newVersion: version };
2816
+ }
2817
+ /**
2818
+ * Rollback to a previous policy version
2819
+ */
2820
+ async rollbackPolicy(version) {
2821
+ const target = this.policyHistory.find((p) => p.version === version);
2822
+ if (!target) return false;
2823
+ if (this.currentPolicy) {
2824
+ this.policyHistory.push(this.currentPolicy);
2825
+ }
2826
+ this.currentPolicy = { ...target, activatedAt: Date.now() };
2827
+ return true;
2828
+ }
2829
+ /**
2830
+ * Evaluate a governance decision
2831
+ */
2832
+ async evaluate(context) {
2833
+ if (!this.currentPolicy) {
2834
+ return {
2835
+ allowed: false,
2836
+ action: "deny",
2837
+ reason: "No policy loaded",
2838
+ policyVersion: "none"
2839
+ };
2840
+ }
2841
+ const cbState = this.getCircuitBreakerState(context.resource);
2842
+ if (cbState === "OPEN") {
2843
+ return {
2844
+ allowed: false,
2845
+ action: "deny",
2846
+ circuitState: "OPEN",
2847
+ reason: `Circuit breaker OPEN for ${context.resource}`,
2848
+ policyVersion: this.currentPolicy.version
2849
+ };
2850
+ }
2851
+ for (const rule of this.currentPolicy.rules) {
2852
+ if (!rule.enabled) continue;
2853
+ const matches = this.evaluateCondition(rule.condition, context);
2854
+ if (!matches) continue;
2855
+ const decision = {
2856
+ allowed: rule.action === "allow",
2857
+ action: rule.action,
2858
+ ruleId: rule.id,
2859
+ ruleName: rule.name,
2860
+ circuitState: cbState,
2861
+ policyVersion: this.currentPolicy.version,
2862
+ reason: `Rule ${rule.name} matched: ${rule.action}`
2863
+ };
2864
+ if (rule.action === "degrade" && rule.degradeTo) {
2865
+ decision.degradationLevel = rule.degradeTo;
2866
+ decision.allowed = true;
2867
+ this.currentDegradationLevel = rule.degradeTo;
2868
+ }
2869
+ if (this.config.onAudit) {
2870
+ try {
2871
+ await this.config.onAudit({
2872
+ type: "governance_decision",
2873
+ data: {
2874
+ action: context.action,
2875
+ resource: context.resource,
2876
+ decision: rule.action,
2877
+ ruleId: rule.id,
2878
+ policyVersion: this.currentPolicy.version
2879
+ }
2880
+ });
2881
+ } catch {
2882
+ }
2883
+ }
2884
+ return decision;
2885
+ }
2886
+ return {
2887
+ allowed: true,
2888
+ action: "allow",
2889
+ reason: "No matching rule, default allow",
2890
+ policyVersion: this.currentPolicy.version,
2891
+ circuitState: cbState
2892
+ };
2893
+ }
2894
+ // ─── Circuit Breaker ─────────────────────────────────────────────
2895
+ /**
2896
+ * Record a success for circuit breaker
2897
+ */
2898
+ recordSuccess(resource) {
2899
+ const cb = this.getOrCreateCircuitBreaker(resource);
2900
+ cb.successCount++;
2901
+ cb.lastSuccessAt = Date.now();
2902
+ if (cb.state === "HALF_OPEN") {
2903
+ if (cb.successCount >= this.config.halfOpenSuccessThreshold) {
2904
+ cb.state = "CLOSED";
2905
+ cb.failureCount = 0;
2906
+ cb.halfOpenAttempts = 0;
2907
+ }
2908
+ }
2909
+ }
2910
+ /**
2911
+ * Record a failure for circuit breaker
2912
+ */
2913
+ recordFailure(resource) {
2914
+ const cb = this.getOrCreateCircuitBreaker(resource);
2915
+ cb.failureCount++;
2916
+ cb.lastFailureAt = Date.now();
2917
+ if (cb.state === "CLOSED" && cb.failureCount >= this.config.circuitBreakerThreshold) {
2918
+ cb.state = "OPEN";
2919
+ cb.openedAt = Date.now();
2920
+ } else if (cb.state === "HALF_OPEN") {
2921
+ cb.state = "OPEN";
2922
+ cb.openedAt = Date.now();
2923
+ cb.halfOpenAttempts++;
2924
+ }
2925
+ }
2926
+ /**
2927
+ * Get circuit breaker state for a resource
2928
+ */
2929
+ getCircuitBreakerState(resource) {
2930
+ const cb = this.circuitBreakers.get(resource);
2931
+ if (!cb) return "CLOSED";
2932
+ if (cb.state === "OPEN") {
2933
+ const elapsed = Date.now() - cb.openedAt;
2934
+ if (elapsed >= this.config.circuitBreakerTimeoutMs) {
2935
+ cb.state = "HALF_OPEN";
2936
+ cb.successCount = 0;
2937
+ }
2938
+ }
2939
+ return cb.state;
2940
+ }
2941
+ // ─── Degradation Chain ───────────────────────────────────────────
2942
+ /**
2943
+ * Get current degradation level
2944
+ */
2945
+ getCurrentDegradationLevel() {
2946
+ return this.config.degradationChain.find((d) => d.id === this.currentDegradationLevel);
2947
+ }
2948
+ /**
2949
+ * Degrade to next level
2950
+ */
2951
+ degradeOneLevel() {
2952
+ const current = this.config.degradationChain.find((d) => d.id === this.currentDegradationLevel);
2953
+ if (!current) return null;
2954
+ const nextLevel = this.config.degradationChain.filter((d) => d.order < current.order).sort((a, b) => b.order - a.order)[0];
2955
+ if (nextLevel) {
2956
+ this.currentDegradationLevel = nextLevel.id;
2957
+ return nextLevel;
2958
+ }
2959
+ return null;
2960
+ }
2961
+ /**
2962
+ * Restore to full capability
2963
+ */
2964
+ restoreFullCapability() {
2965
+ this.currentDegradationLevel = "full";
2966
+ }
2967
+ /**
2968
+ * Check if a capability is available at current degradation level
2969
+ */
2970
+ isCapabilityAvailable(capability) {
2971
+ const level = this.getCurrentDegradationLevel();
2972
+ if (!level) return false;
2973
+ return level.capabilities.includes("all") || level.capabilities.includes(capability);
2974
+ }
2975
+ // ─── Status ──────────────────────────────────────────────────────
2976
+ /**
2977
+ * Get full governance status
2978
+ */
2979
+ getStatus() {
2980
+ return {
2981
+ policyVersion: this.currentPolicy?.version ?? null,
2982
+ ruleCount: this.currentPolicy?.rules.length ?? 0,
2983
+ degradationLevel: this.currentDegradationLevel,
2984
+ circuitBreakers: Array.from(this.circuitBreakers.values()),
2985
+ policyHistoryCount: this.policyHistory.length
2986
+ };
2987
+ }
2988
+ // ─── Internal ────────────────────────────────────────────────────
2989
+ evaluateCondition(condition, context) {
2990
+ if (condition === "*") return true;
2991
+ if (condition.startsWith("action:")) {
2992
+ return context.action === condition.substring(7);
2993
+ }
2994
+ if (condition.startsWith("resource:")) {
2995
+ return context.resource.includes(condition.substring(9));
2996
+ }
2997
+ if (condition.startsWith("agent:")) {
2998
+ return context.agentId === condition.substring(6);
2999
+ }
3000
+ return false;
3001
+ }
3002
+ getOrCreateCircuitBreaker(resource) {
3003
+ let cb = this.circuitBreakers.get(resource);
3004
+ if (!cb) {
3005
+ cb = {
3006
+ name: resource,
3007
+ state: "CLOSED",
3008
+ failureCount: 0,
3009
+ successCount: 0,
3010
+ lastFailureAt: 0,
3011
+ lastSuccessAt: 0,
3012
+ openedAt: 0,
3013
+ halfOpenAttempts: 0
3014
+ };
3015
+ this.circuitBreakers.set(resource, cb);
3016
+ }
3017
+ return cb;
3018
+ }
3019
+ };
3020
+
3021
+ // src/contextAccelerator.ts
3022
+ var DEFAULT_CA_CONFIG = {
3023
+ maxCacheEntries: 500,
3024
+ defaultTtlMs: 3e5,
3025
+ // 5 minutes
3026
+ tokenBudget: 8e3,
3027
+ compressionTarget: 0.5,
3028
+ priorityWeights: {
3029
+ critical: 100,
3030
+ high: 75,
3031
+ medium: 50,
3032
+ low: 25
3033
+ }
3034
+ };
3035
+ function estimateTokens(text) {
3036
+ return Math.ceil(text.length / 3.5);
3037
+ }
3038
+ function defaultCompressor(content, targetTokens) {
3039
+ const currentTokens = estimateTokens(content);
3040
+ if (currentTokens <= targetTokens) return content;
3041
+ const ratio = targetTokens / currentTokens;
3042
+ const targetLength = Math.floor(content.length * ratio);
3043
+ if (targetLength < 50) return content.substring(0, 50) + "...";
3044
+ return content.substring(0, targetLength) + "...[compressed]";
3045
+ }
3046
+ var ContextAccelerator = class {
3047
+ cache = /* @__PURE__ */ new Map();
3048
+ prefetchRules = /* @__PURE__ */ new Map();
3049
+ config;
3050
+ stats = {
3051
+ totalHits: 0,
3052
+ totalMisses: 0,
3053
+ totalEvictions: 0,
3054
+ totalCompressions: 0,
3055
+ totalAssemblies: 0
3056
+ };
3057
+ constructor(config) {
3058
+ this.config = { ...DEFAULT_CA_CONFIG, ...config };
3059
+ }
3060
+ /**
3061
+ * Put a fragment into cache
3062
+ */
3063
+ put(fragment) {
3064
+ this.evictExpired();
3065
+ if (this.cache.size >= this.config.maxCacheEntries) {
3066
+ this.evictLRU();
3067
+ }
3068
+ this.cache.set(fragment.id, {
3069
+ fragment,
3070
+ accessCount: 0,
3071
+ lastAccessedAt: Date.now(),
3072
+ createdAt: Date.now(),
3073
+ expiresAt: Date.now() + (fragment.ttlMs || this.config.defaultTtlMs)
3074
+ });
3075
+ }
3076
+ /**
3077
+ * Get a fragment from cache
3078
+ */
3079
+ get(id) {
3080
+ const entry = this.cache.get(id);
3081
+ if (!entry) {
3082
+ this.stats.totalMisses++;
3083
+ return null;
3084
+ }
3085
+ if (Date.now() > entry.expiresAt) {
3086
+ this.cache.delete(id);
3087
+ this.stats.totalMisses++;
3088
+ return null;
3089
+ }
3090
+ entry.accessCount++;
3091
+ entry.lastAccessedAt = Date.now();
3092
+ this.stats.totalHits++;
3093
+ return entry.fragment;
3094
+ }
3095
+ /**
3096
+ * Assemble context from fragments within token budget
3097
+ */
3098
+ async assemble(fragmentIds, additionalFragments, budgetOverride) {
3099
+ const startTime = Date.now();
3100
+ const budget = budgetOverride ?? this.config.tokenBudget;
3101
+ let cacheHits = 0;
3102
+ let cacheMisses = 0;
3103
+ const allFragments = [];
3104
+ for (const id of fragmentIds) {
3105
+ const fragment = this.get(id);
3106
+ if (fragment) {
3107
+ allFragments.push(fragment);
3108
+ cacheHits++;
3109
+ } else {
3110
+ cacheMisses++;
3111
+ }
3112
+ }
3113
+ if (additionalFragments) {
3114
+ allFragments.push(...additionalFragments);
3115
+ }
3116
+ const weights = this.config.priorityWeights;
3117
+ allFragments.sort((a, b) => {
3118
+ const wDiff = (weights[b.priority] ?? 0) - (weights[a.priority] ?? 0);
3119
+ if (wDiff !== 0) return wDiff;
3120
+ return b.timestamp - a.timestamp;
3121
+ });
3122
+ const selected = [];
3123
+ let totalTokens = 0;
3124
+ let droppedCount = 0;
3125
+ let compressedCount = 0;
3126
+ for (const fragment of allFragments) {
3127
+ if (totalTokens >= budget) {
3128
+ droppedCount++;
3129
+ continue;
3130
+ }
3131
+ const remaining = budget - totalTokens;
3132
+ if (fragment.tokenCount <= remaining) {
3133
+ selected.push(fragment);
3134
+ totalTokens += fragment.tokenCount;
3135
+ } else if (fragment.priority === "critical" || fragment.priority === "high") {
3136
+ const compressor = this.config.compressor ?? defaultCompressor;
3137
+ const compressed = compressor(fragment.content, remaining);
3138
+ const compressedTokens = estimateTokens(compressed);
3139
+ selected.push({
3140
+ ...fragment,
3141
+ content: compressed,
3142
+ tokenCount: compressedTokens,
3143
+ compressed: true
3144
+ });
3145
+ totalTokens += compressedTokens;
3146
+ compressedCount++;
3147
+ this.stats.totalCompressions++;
3148
+ } else {
3149
+ droppedCount++;
3150
+ }
3151
+ }
3152
+ this.stats.totalAssemblies++;
3153
+ const result = {
3154
+ fragments: selected,
3155
+ totalTokens,
3156
+ budgetUsed: budget > 0 ? totalTokens / budget : 0,
3157
+ droppedCount,
3158
+ compressedCount,
3159
+ cacheHits,
3160
+ cacheMisses,
3161
+ assemblyTimeMs: Date.now() - startTime
3162
+ };
3163
+ if (this.config.onAudit) {
3164
+ try {
3165
+ await this.config.onAudit({
3166
+ type: "context_assembled",
3167
+ data: {
3168
+ totalTokens,
3169
+ budgetUsed: result.budgetUsed,
3170
+ fragmentCount: selected.length,
3171
+ droppedCount,
3172
+ compressedCount,
3173
+ cacheHits,
3174
+ cacheMisses,
3175
+ assemblyTimeMs: result.assemblyTimeMs
3176
+ }
3177
+ });
3178
+ } catch {
3179
+ }
3180
+ }
3181
+ return result;
3182
+ }
3183
+ /**
3184
+ * Register a prefetch rule
3185
+ */
3186
+ addPrefetchRule(rule) {
3187
+ this.prefetchRules.set(rule.id, rule);
3188
+ }
3189
+ /**
3190
+ * Execute prefetch based on task type
3191
+ */
3192
+ async prefetch(taskType, fragmentLoader) {
3193
+ const matchingRules = Array.from(this.prefetchRules.values()).filter(
3194
+ (r) => r.enabled && taskType.includes(r.trigger)
3195
+ );
3196
+ if (matchingRules.length === 0) return 0;
3197
+ const idsToFetch = /* @__PURE__ */ new Set();
3198
+ for (const rule of matchingRules) {
3199
+ for (const id of rule.fragmentIds) {
3200
+ if (!this.cache.has(id)) {
3201
+ idsToFetch.add(id);
3202
+ }
3203
+ }
3204
+ }
3205
+ if (idsToFetch.size === 0) return 0;
3206
+ const fragments = await fragmentLoader(Array.from(idsToFetch));
3207
+ for (const f of fragments) {
3208
+ this.put(f);
3209
+ }
3210
+ return fragments.length;
3211
+ }
3212
+ /**
3213
+ * Invalidate cache entries
3214
+ */
3215
+ invalidate(ids) {
3216
+ let count = 0;
3217
+ for (const id of ids) {
3218
+ if (this.cache.delete(id)) count++;
3219
+ }
3220
+ return count;
3221
+ }
3222
+ /**
3223
+ * Get cache stats
3224
+ */
3225
+ getStats() {
3226
+ const total = this.stats.totalHits + this.stats.totalMisses;
3227
+ return {
3228
+ cacheSize: this.cache.size,
3229
+ maxSize: this.config.maxCacheEntries,
3230
+ hitRate: total > 0 ? this.stats.totalHits / total : 0,
3231
+ ...this.stats,
3232
+ prefetchRuleCount: this.prefetchRules.size
3233
+ };
3234
+ }
3235
+ /**
3236
+ * Clear all cache
3237
+ */
3238
+ clear() {
3239
+ this.cache.clear();
3240
+ }
3241
+ // ─── Internal ────────────────────────────────────────────────────
3242
+ evictExpired() {
3243
+ const now = Date.now();
3244
+ for (const [id, entry] of this.cache) {
3245
+ if (now > entry.expiresAt) {
3246
+ this.cache.delete(id);
3247
+ this.stats.totalEvictions++;
3248
+ }
3249
+ }
3250
+ }
3251
+ evictLRU() {
3252
+ let oldestId = null;
3253
+ let oldestAccess = Infinity;
3254
+ for (const [id, entry] of this.cache) {
3255
+ if (entry.lastAccessedAt < oldestAccess) {
3256
+ oldestAccess = entry.lastAccessedAt;
3257
+ oldestId = id;
3258
+ }
3259
+ }
3260
+ if (oldestId) {
3261
+ this.cache.delete(oldestId);
3262
+ this.stats.totalEvictions++;
3263
+ }
3264
+ }
3265
+ };
3266
+
688
3267
  // src/index.ts
689
3268
  var DEFAULT_RULES = [
690
3269
  // --- HTTP Proxy: Dangerous outbound calls ---
@@ -919,7 +3498,7 @@ var RISK_SCORES = {
919
3498
  high: 70,
920
3499
  critical: 95
921
3500
  };
922
- var ENGINE_VERSION = "3.3.0";
3501
+ var ENGINE_VERSION = "3.4.0";
923
3502
  var ENGINE_VERSION_CHECK_URL = "https://api.sovr.inc/api/sovr/v1/version/check";
924
3503
  var ENGINE_TIER_LIMITS = {
925
3504
  free: { evaluationsPerMonth: 50, irreversibleAllowsPerMonth: 0 },
@@ -1175,13 +3754,42 @@ var index_default = PolicyEngine;
1175
3754
  // Annotate the CommonJS export names for ESM import in node:
1176
3755
  0 && (module.exports = {
1177
3756
  AdaptiveThresholdManager,
3757
+ AutoHardenEngine,
3758
+ ContextAccelerator,
3759
+ CostGateEnhancedEngine,
3760
+ DEFAULT_CA_CONFIG,
3761
+ DEFAULT_GE_CONFIG,
3762
+ DEFAULT_HARD_RULES,
1178
3763
  DEFAULT_RULES,
3764
+ DEFAULT_SCORING_WEIGHTS,
3765
+ DEFAULT_TSA_CONFIG,
3766
+ EvolutionChannelEngine,
1179
3767
  FeatureSwitchesManager,
3768
+ GovernanceEnhancer,
3769
+ MultiLevelBudgetEngine,
1180
3770
  PolicyEngine,
1181
3771
  PricingRulesEngine,
3772
+ RecalculationEngine,
1182
3773
  SOVR_FEATURE_SWITCHES,
3774
+ SemanticDriftDetectorEngine,
3775
+ TimeSeriesAggregator,
3776
+ TwoPhaseRouter,
3777
+ ValuationModel,
1183
3778
  compileFromJSON,
1184
3779
  compileRuleSet,
3780
+ createAutoHardenEngine,
3781
+ createCostGateEnhanced,
3782
+ createEvolutionChannel,
3783
+ createMultiLevelBudget,
3784
+ createRecalculationEngine,
3785
+ createSemanticDriftDetector,
3786
+ estimateCost,
1185
3787
  evaluateRules,
1186
- registerFunction
3788
+ getAccuracyStats,
3789
+ getModelPricingTable,
3790
+ getToolPricingTable,
3791
+ recordActualCost,
3792
+ registerFunction,
3793
+ updateModelPricing,
3794
+ updateToolPricing
1187
3795
  });