@oneuptime/common 9.2.16 → 9.2.18

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.
Files changed (133) hide show
  1. package/Models/DatabaseModels/CodeRepository.ts +664 -0
  2. package/Models/DatabaseModels/Index.ts +8 -0
  3. package/Models/DatabaseModels/LlmLog.ts +818 -0
  4. package/Models/DatabaseModels/LlmProvider.ts +21 -0
  5. package/Models/DatabaseModels/Project.ts +206 -0
  6. package/Models/DatabaseModels/ServiceCatalogCodeRepository.ts +549 -0
  7. package/Server/API/AIBillingAPI.ts +126 -0
  8. package/Server/API/AlertAPI.ts +139 -0
  9. package/Server/API/GitHubAPI.ts +360 -0
  10. package/Server/API/IncidentAPI.ts +258 -0
  11. package/Server/API/ScheduledMaintenanceAPI.ts +164 -0
  12. package/Server/EnvironmentConfig.ts +44 -0
  13. package/Server/Infrastructure/Postgres/SchemaMigrations/1765580181582-MigrationName.ts +79 -0
  14. package/Server/Infrastructure/Postgres/SchemaMigrations/1765633554715-MigrationName.ts +75 -0
  15. package/Server/Infrastructure/Postgres/SchemaMigrations/1765801357168-MigrationName.ts +32 -0
  16. package/Server/Infrastructure/Postgres/SchemaMigrations/1765810218488-MigrationName.ts +69 -0
  17. package/Server/Infrastructure/Postgres/SchemaMigrations/1765830758857-MigrationName.ts +111 -0
  18. package/Server/Infrastructure/Postgres/SchemaMigrations/1765834537501-MigrationName.ts +39 -0
  19. package/Server/Infrastructure/Postgres/SchemaMigrations/Index.ts +12 -0
  20. package/Server/Services/AIBillingService.ts +247 -0
  21. package/Server/Services/AIService.ts +238 -0
  22. package/Server/Services/CodeRepositoryService.ts +10 -0
  23. package/Server/Services/IncidentService.ts +88 -0
  24. package/Server/Services/Index.ts +2 -0
  25. package/Server/Services/LlmLogService.ts +14 -0
  26. package/Server/Services/LlmProviderService.ts +58 -0
  27. package/Server/Services/ServiceCatalogCodeRepositoryService.ts +55 -0
  28. package/Server/Utils/AI/AlertAIContextBuilder.ts +264 -0
  29. package/Server/Utils/AI/IncidentAIContextBuilder.ts +710 -0
  30. package/Server/Utils/AI/ScheduledMaintenanceAIContextBuilder.ts +345 -0
  31. package/Server/Utils/CodeRepository/GitHub/GitHub.ts +226 -0
  32. package/Server/Utils/LLM/LLMService.ts +276 -0
  33. package/Server/Utils/Workspace/MicrosoftTeams/MicrosoftTeams.ts +166 -0
  34. package/Server/Utils/Workspace/Slack/Slack.ts +134 -0
  35. package/Server/Utils/Workspace/Workspace.ts +126 -0
  36. package/Tests/Types/Domain.test.ts +24 -3
  37. package/Types/CodeRepository/CodeRepositoryType.ts +1 -1
  38. package/Types/Domain.ts +21 -24
  39. package/Types/LlmLogStatus.ts +7 -0
  40. package/Types/Permission.ts +87 -0
  41. package/Types/ServiceCatalog/CodeRepositoryImprovementAction.ts +9 -0
  42. package/UI/Components/AI/AILoader.tsx +95 -0
  43. package/UI/Components/AI/GenerateFromAIModal.tsx +432 -0
  44. package/UI/Components/Modal/Modal.tsx +6 -1
  45. package/build/dist/Models/DatabaseModels/CodeRepository.js +689 -0
  46. package/build/dist/Models/DatabaseModels/CodeRepository.js.map +1 -0
  47. package/build/dist/Models/DatabaseModels/Index.js +7 -0
  48. package/build/dist/Models/DatabaseModels/Index.js.map +1 -1
  49. package/build/dist/Models/DatabaseModels/LlmLog.js +856 -0
  50. package/build/dist/Models/DatabaseModels/LlmLog.js.map +1 -0
  51. package/build/dist/Models/DatabaseModels/LlmProvider.js +22 -0
  52. package/build/dist/Models/DatabaseModels/LlmProvider.js.map +1 -1
  53. package/build/dist/Models/DatabaseModels/Project.js +220 -0
  54. package/build/dist/Models/DatabaseModels/Project.js.map +1 -1
  55. package/build/dist/Models/DatabaseModels/ServiceCatalogCodeRepository.js +565 -0
  56. package/build/dist/Models/DatabaseModels/ServiceCatalogCodeRepository.js.map +1 -0
  57. package/build/dist/Server/API/AIBillingAPI.js +58 -0
  58. package/build/dist/Server/API/AIBillingAPI.js.map +1 -0
  59. package/build/dist/Server/API/AlertAPI.js +94 -0
  60. package/build/dist/Server/API/AlertAPI.js.map +1 -0
  61. package/build/dist/Server/API/GitHubAPI.js +207 -0
  62. package/build/dist/Server/API/GitHubAPI.js.map +1 -0
  63. package/build/dist/Server/API/IncidentAPI.js +171 -1
  64. package/build/dist/Server/API/IncidentAPI.js.map +1 -1
  65. package/build/dist/Server/API/ScheduledMaintenanceAPI.js +103 -0
  66. package/build/dist/Server/API/ScheduledMaintenanceAPI.js.map +1 -0
  67. package/build/dist/Server/EnvironmentConfig.js +31 -0
  68. package/build/dist/Server/EnvironmentConfig.js.map +1 -1
  69. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1765580181582-MigrationName.js +34 -0
  70. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1765580181582-MigrationName.js.map +1 -0
  71. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1765633554715-MigrationName.js +32 -0
  72. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1765633554715-MigrationName.js.map +1 -0
  73. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1765801357168-MigrationName.js +38 -0
  74. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1765801357168-MigrationName.js.map +1 -0
  75. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1765810218488-MigrationName.js +30 -0
  76. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1765810218488-MigrationName.js.map +1 -0
  77. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1765830758857-MigrationName.js +44 -0
  78. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1765830758857-MigrationName.js.map +1 -0
  79. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1765834537501-MigrationName.js +22 -0
  80. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1765834537501-MigrationName.js.map +1 -0
  81. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js +12 -0
  82. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js.map +1 -1
  83. package/build/dist/Server/Services/AIBillingService.js +187 -0
  84. package/build/dist/Server/Services/AIBillingService.js.map +1 -0
  85. package/build/dist/Server/Services/AIService.js +184 -0
  86. package/build/dist/Server/Services/AIService.js.map +1 -0
  87. package/build/dist/Server/Services/CodeRepositoryService.js +9 -0
  88. package/build/dist/Server/Services/CodeRepositoryService.js.map +1 -0
  89. package/build/dist/Server/Services/IncidentService.js +60 -0
  90. package/build/dist/Server/Services/IncidentService.js.map +1 -1
  91. package/build/dist/Server/Services/Index.js +2 -0
  92. package/build/dist/Server/Services/Index.js.map +1 -1
  93. package/build/dist/Server/Services/LlmLogService.js +13 -0
  94. package/build/dist/Server/Services/LlmLogService.js.map +1 -0
  95. package/build/dist/Server/Services/LlmProviderService.js +65 -0
  96. package/build/dist/Server/Services/LlmProviderService.js.map +1 -1
  97. package/build/dist/Server/Services/ServiceCatalogCodeRepositoryService.js +54 -0
  98. package/build/dist/Server/Services/ServiceCatalogCodeRepositoryService.js.map +1 -0
  99. package/build/dist/Server/Utils/AI/AlertAIContextBuilder.js +238 -0
  100. package/build/dist/Server/Utils/AI/AlertAIContextBuilder.js.map +1 -0
  101. package/build/dist/Server/Utils/AI/IncidentAIContextBuilder.js +597 -0
  102. package/build/dist/Server/Utils/AI/IncidentAIContextBuilder.js.map +1 -0
  103. package/build/dist/Server/Utils/AI/ScheduledMaintenanceAIContextBuilder.js +311 -0
  104. package/build/dist/Server/Utils/AI/ScheduledMaintenanceAIContextBuilder.js.map +1 -0
  105. package/build/dist/Server/Utils/CodeRepository/GitHub/GitHub.js +163 -0
  106. package/build/dist/Server/Utils/CodeRepository/GitHub/GitHub.js.map +1 -1
  107. package/build/dist/Server/Utils/LLM/LLMService.js +225 -0
  108. package/build/dist/Server/Utils/LLM/LLMService.js.map +1 -0
  109. package/build/dist/Server/Utils/Workspace/MicrosoftTeams/MicrosoftTeams.js +110 -0
  110. package/build/dist/Server/Utils/Workspace/MicrosoftTeams/MicrosoftTeams.js.map +1 -1
  111. package/build/dist/Server/Utils/Workspace/Slack/Slack.js +89 -0
  112. package/build/dist/Server/Utils/Workspace/Slack/Slack.js.map +1 -1
  113. package/build/dist/Server/Utils/Workspace/Workspace.js +80 -0
  114. package/build/dist/Server/Utils/Workspace/Workspace.js.map +1 -1
  115. package/build/dist/Tests/Types/Domain.test.js +19 -3
  116. package/build/dist/Tests/Types/Domain.test.js.map +1 -1
  117. package/build/dist/Types/CodeRepository/CodeRepositoryType.js +1 -1
  118. package/build/dist/Types/CodeRepository/CodeRepositoryType.js.map +1 -1
  119. package/build/dist/Types/Domain.js +18 -16
  120. package/build/dist/Types/Domain.js.map +1 -1
  121. package/build/dist/Types/LlmLogStatus.js +8 -0
  122. package/build/dist/Types/LlmLogStatus.js.map +1 -0
  123. package/build/dist/Types/Permission.js +74 -0
  124. package/build/dist/Types/Permission.js.map +1 -1
  125. package/build/dist/Types/ServiceCatalog/CodeRepositoryImprovementAction.js +10 -0
  126. package/build/dist/Types/ServiceCatalog/CodeRepositoryImprovementAction.js.map +1 -0
  127. package/build/dist/UI/Components/AI/AILoader.js +64 -0
  128. package/build/dist/UI/Components/AI/AILoader.js.map +1 -0
  129. package/build/dist/UI/Components/AI/GenerateFromAIModal.js +320 -0
  130. package/build/dist/UI/Components/AI/GenerateFromAIModal.js.map +1 -0
  131. package/build/dist/UI/Components/Modal/Modal.js +6 -1
  132. package/build/dist/UI/Components/Modal/Modal.js.map +1 -1
  133. package/package.json +1 -1
@@ -0,0 +1,187 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { IsBillingEnabled, NotificationSlackWebhookOnSubscriptionUpdate, } from "../EnvironmentConfig";
11
+ import logger from "../Utils/Logger";
12
+ import BaseService from "./BaseService";
13
+ import BillingService from "./BillingService";
14
+ import ProjectService from "./ProjectService";
15
+ import BadDataException from "../../Types/Exception/BadDataException";
16
+ import ObjectID from "../../Types/ObjectID";
17
+ import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
18
+ import SlackUtil from "../Utils/Workspace/Slack/Slack";
19
+ import URL from "../../Types/API/URL";
20
+ export class AIBillingService extends BaseService {
21
+ constructor() {
22
+ super();
23
+ }
24
+ async rechargeBalance(projectId, amountInUSD) {
25
+ if (!IsBillingEnabled) {
26
+ throw new BadDataException("Billing is not enabled");
27
+ }
28
+ const project = await ProjectService.findOneById({
29
+ id: projectId,
30
+ select: {
31
+ aiCurrentBalanceInUSDCents: true,
32
+ enableAutoRechargeAiBalance: true,
33
+ enableAi: true,
34
+ autoAiRechargeByBalanceInUSD: true,
35
+ autoRechargeAiWhenCurrentBalanceFallsInUSD: true,
36
+ paymentProviderCustomerId: true,
37
+ name: true,
38
+ failedAiBalanceChargeNotificationSentToOwners: true,
39
+ },
40
+ props: {
41
+ isRoot: true,
42
+ },
43
+ });
44
+ if (!project) {
45
+ return 0;
46
+ }
47
+ try {
48
+ if (!(await BillingService.hasPaymentMethods(project.paymentProviderCustomerId))) {
49
+ if (!project.failedAiBalanceChargeNotificationSentToOwners) {
50
+ await ProjectService.updateOneById({
51
+ data: {
52
+ failedAiBalanceChargeNotificationSentToOwners: true,
53
+ },
54
+ id: project.id,
55
+ props: {
56
+ isRoot: true,
57
+ },
58
+ });
59
+ await ProjectService.sendEmailToProjectOwners(project.id, "ACTION REQUIRED: AI Balance Recharge Failed for project - " +
60
+ (project.name || ""), `We have tried to recharge your AI balance for project - ${project.name || ""} and failed. We could not find a payment method for the project. Please add a payment method in Project Settings.`);
61
+ }
62
+ throw new BadDataException("No payment methods found for the project. Please add a payment method in Project Settings to continue.");
63
+ }
64
+ // recharge balance
65
+ const updatedAmount = Math.floor((project.aiCurrentBalanceInUSDCents || 0) + amountInUSD * 100);
66
+ // If the recharge is successful, then update the project balance.
67
+ await BillingService.generateInvoiceAndChargeCustomer(project.paymentProviderCustomerId, "AI Balance Recharge", amountInUSD);
68
+ await ProjectService.updateOneById({
69
+ data: {
70
+ aiCurrentBalanceInUSDCents: updatedAmount,
71
+ failedAiBalanceChargeNotificationSentToOwners: false, // reset this flag
72
+ lowAiBalanceNotificationSentToOwners: false, // reset this flag
73
+ notEnabledAiNotificationSentToOwners: false,
74
+ },
75
+ id: project.id,
76
+ props: {
77
+ isRoot: true,
78
+ },
79
+ });
80
+ await ProjectService.sendEmailToProjectOwners(project.id, "AI Balance Recharge Successful for project - " + (project.name || ""), `We have successfully recharged your AI balance for project - ${project.name || ""} by ${amountInUSD} USD. Your current balance is ${updatedAmount / 100} USD.`);
81
+ // Send Slack notification for balance refill
82
+ this.sendBalanceRefillSlackNotification({
83
+ project: project,
84
+ amountInUSD: amountInUSD,
85
+ currentBalanceInUSD: updatedAmount / 100,
86
+ }).catch((error) => {
87
+ logger.error("Error sending slack message for AI balance refill: " + error);
88
+ });
89
+ project.aiCurrentBalanceInUSDCents = updatedAmount;
90
+ return updatedAmount;
91
+ }
92
+ catch (err) {
93
+ await ProjectService.updateOneById({
94
+ data: {
95
+ failedAiBalanceChargeNotificationSentToOwners: true,
96
+ },
97
+ id: project.id,
98
+ props: {
99
+ isRoot: true,
100
+ },
101
+ });
102
+ await ProjectService.sendEmailToProjectOwners(project.id, "ACTION REQUIRED: AI Balance Recharge Failed for project - " +
103
+ (project.name || ""), `We have tried to recharge your AI balance for project - ${project.name || ""} and failed. Please make sure your payment method is up to date and has sufficient balance. You can add new payment methods in Project Settings.`);
104
+ logger.error(err);
105
+ throw err;
106
+ }
107
+ }
108
+ async rechargeIfBalanceIsLow(projectId, options) {
109
+ let project = null;
110
+ if (projectId && IsBillingEnabled) {
111
+ // check payment methods.
112
+ project = await ProjectService.findOneById({
113
+ id: projectId,
114
+ select: {
115
+ aiCurrentBalanceInUSDCents: true,
116
+ enableAutoRechargeAiBalance: true,
117
+ autoAiRechargeByBalanceInUSD: true,
118
+ autoRechargeAiWhenCurrentBalanceFallsInUSD: true,
119
+ },
120
+ props: {
121
+ isRoot: true,
122
+ },
123
+ });
124
+ const autoRechargeAiWhenCurrentBalanceFallsInUSD = (options === null || options === void 0 ? void 0 : options.autoRechargeAiWhenCurrentBalanceFallsInUSD) ||
125
+ (project === null || project === void 0 ? void 0 : project.autoRechargeAiWhenCurrentBalanceFallsInUSD) ||
126
+ 0;
127
+ const autoAiRechargeByBalanceInUSD = (options === null || options === void 0 ? void 0 : options.autoAiRechargeByBalanceInUSD) ||
128
+ (project === null || project === void 0 ? void 0 : project.autoAiRechargeByBalanceInUSD) ||
129
+ 0;
130
+ const enableAutoRechargeAiBalance = options
131
+ ? options.enableAutoRechargeAiBalance
132
+ : (project === null || project === void 0 ? void 0 : project.enableAutoRechargeAiBalance) || false;
133
+ if (!project) {
134
+ return 0;
135
+ }
136
+ if (enableAutoRechargeAiBalance &&
137
+ autoAiRechargeByBalanceInUSD &&
138
+ autoRechargeAiWhenCurrentBalanceFallsInUSD) {
139
+ if ((project.aiCurrentBalanceInUSDCents || 0) / 100 <
140
+ autoRechargeAiWhenCurrentBalanceFallsInUSD) {
141
+ const updatedAmount = await this.rechargeBalance(projectId, autoAiRechargeByBalanceInUSD);
142
+ project.aiCurrentBalanceInUSDCents = updatedAmount;
143
+ }
144
+ }
145
+ }
146
+ return (project === null || project === void 0 ? void 0 : project.aiCurrentBalanceInUSDCents) || 0;
147
+ }
148
+ async sendBalanceRefillSlackNotification(data) {
149
+ var _a, _b;
150
+ const { project, amountInUSD, currentBalanceInUSD } = data;
151
+ if (NotificationSlackWebhookOnSubscriptionUpdate) {
152
+ const slackMessage = `*AI Balance Refilled:*
153
+ *Project Name:* ${((_a = project.name) === null || _a === void 0 ? void 0 : _a.toString()) || "N/A"}
154
+ *Project ID:* ${((_b = project.id) === null || _b === void 0 ? void 0 : _b.toString()) || "N/A"}
155
+ *Refill Amount:* $${amountInUSD} USD
156
+ *Current Balance:* $${currentBalanceInUSD} USD
157
+
158
+ ${project.createdOwnerName && project.createdOwnerEmail ? `*Project Created By:* ${project.createdOwnerName.toString()} (${project.createdOwnerEmail.toString()})` : ""}`;
159
+ SlackUtil.sendMessageToChannelViaIncomingWebhook({
160
+ url: URL.fromString(NotificationSlackWebhookOnSubscriptionUpdate),
161
+ text: slackMessage,
162
+ }).catch((error) => {
163
+ logger.error("Error sending slack message for AI balance refill: " + error);
164
+ });
165
+ }
166
+ }
167
+ }
168
+ __decorate([
169
+ CaptureSpan(),
170
+ __metadata("design:type", Function),
171
+ __metadata("design:paramtypes", [ObjectID, Number]),
172
+ __metadata("design:returntype", Promise)
173
+ ], AIBillingService.prototype, "rechargeBalance", null);
174
+ __decorate([
175
+ CaptureSpan(),
176
+ __metadata("design:type", Function),
177
+ __metadata("design:paramtypes", [ObjectID, Object]),
178
+ __metadata("design:returntype", Promise)
179
+ ], AIBillingService.prototype, "rechargeIfBalanceIsLow", null);
180
+ __decorate([
181
+ CaptureSpan(),
182
+ __metadata("design:type", Function),
183
+ __metadata("design:paramtypes", [Object]),
184
+ __metadata("design:returntype", Promise)
185
+ ], AIBillingService.prototype, "sendBalanceRefillSlackNotification", null);
186
+ export default new AIBillingService();
187
+ //# sourceMappingURL=AIBillingService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AIBillingService.js","sourceRoot":"","sources":["../../../../Server/Services/AIBillingService.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EACL,gBAAgB,EAChB,4CAA4C,GAC7C,MAAM,sBAAsB,CAAC;AAC9B,OAAO,MA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I,KAAK;gBACnC,CAAA,MAAA,OAAO,CAAC,EAAE,0CAAE,QAAQ,EAAE,KAAI,KAAK;oBAC3B,WAAW;sBACT,mBAAmB;;EAEvC,OAAO,CAAC,gBAAgB,IAAI,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,yBAAyB,OAAO,CAAC,gBAAgB,CAAC,QAAQ,EAAE,KAAK,OAAO,CAAC,iBAAiB,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;YAEpK,SAAS,CAAC,sCAAsC,CAAC;gBAC/C,GAAG,EAAE,GAAG,CAAC,UAAU,CAAC,4CAA4C,CAAC;gBACjE,IAAI,EAAE,YAAY;aACnB,CAAC,CAAC,KAAK,CAAC,CAAC,KAAgB,EAAE,EAAE;gBAC5B,MAAM,CAAC,KAAK,CACV,qDAAqD,GAAG,KAAK,CAC9D,CAAC;YACJ,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF;AA9Nc;IADZ,WAAW,EAAE;;qCAED,QAAQ;;uDAgIpB;AAGY;IADZ,WAAW,EAAE;;qCAED,QAAQ;;8DA4DpB;AAGa;IADb,WAAW,EAAE;;;;0EA0Bb;AAGH,eAAe,IAAI,gBAAgB,EAAE,CAAC"}
@@ -0,0 +1,184 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { IsBillingEnabled } from "../EnvironmentConfig";
11
+ import BaseService from "./BaseService";
12
+ import LlmProviderService from "./LlmProviderService";
13
+ import LlmLogService from "./LlmLogService";
14
+ import ProjectService from "./ProjectService";
15
+ import AIBillingService from "./AIBillingService";
16
+ import LLMService from "../Utils/LLM/LLMService";
17
+ import LlmLog from "../../Models/DatabaseModels/LlmLog";
18
+ import LlmLogStatus from "../../Types/LlmLogStatus";
19
+ import BadDataException from "../../Types/Exception/BadDataException";
20
+ import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
21
+ import logger from "../Utils/Logger";
22
+ export class Service extends BaseService {
23
+ constructor() {
24
+ super();
25
+ }
26
+ async executeWithLogging(request) {
27
+ var _a, _b;
28
+ const startTime = new Date();
29
+ // Get LLM provider for the project
30
+ const llmProvider = await LlmProviderService.getLLMProviderForProject(request.projectId);
31
+ if (!llmProvider) {
32
+ throw new BadDataException("No LLM provider configured for this project. Please configure an LLM provider in Settings > AI > LLM Providers.");
33
+ }
34
+ if (!llmProvider.llmType) {
35
+ throw new BadDataException("LLM provider type is not configured properly.");
36
+ }
37
+ // Create log entry (will be updated after completion)
38
+ const logEntry = new LlmLog();
39
+ logEntry.projectId = request.projectId;
40
+ logEntry.isGlobalProvider = llmProvider.isGlobalLlm || false;
41
+ logEntry.feature = request.feature;
42
+ logEntry.requestPrompt = request.messages
43
+ .map((m) => {
44
+ return m.content;
45
+ })
46
+ .join("\n")
47
+ .substring(0, 5000); // Store first 5000 chars
48
+ logEntry.requestStartedAt = startTime;
49
+ // Set optional fields only if they have values
50
+ if (llmProvider.id) {
51
+ logEntry.llmProviderId = llmProvider.id;
52
+ }
53
+ if (llmProvider.name) {
54
+ logEntry.llmProviderName = llmProvider.name;
55
+ }
56
+ if (llmProvider.llmType) {
57
+ logEntry.llmType = llmProvider.llmType;
58
+ }
59
+ if (llmProvider.modelName) {
60
+ logEntry.modelName = llmProvider.modelName;
61
+ }
62
+ if (request.userId) {
63
+ logEntry.userId = request.userId;
64
+ }
65
+ if (request.incidentId) {
66
+ logEntry.incidentId = request.incidentId;
67
+ }
68
+ if (request.alertId) {
69
+ logEntry.alertId = request.alertId;
70
+ }
71
+ if (request.scheduledMaintenanceId) {
72
+ logEntry.scheduledMaintenanceId = request.scheduledMaintenanceId;
73
+ }
74
+ // Check if billing should apply
75
+ const shouldBill = IsBillingEnabled && (llmProvider.isGlobalLlm || false);
76
+ // Check balance if billing enabled and using global provider
77
+ if (shouldBill) {
78
+ const project = await ProjectService.findOneById({
79
+ id: request.projectId,
80
+ select: { aiCurrentBalanceInUSDCents: true },
81
+ props: { isRoot: true },
82
+ });
83
+ if (!project || (project.aiCurrentBalanceInUSDCents || 0) <= 0) {
84
+ logEntry.status = LlmLogStatus.InsufficientBalance;
85
+ logEntry.statusMessage = "Insufficient AI balance";
86
+ logEntry.requestCompletedAt = new Date();
87
+ logEntry.durationMs = new Date().getTime() - startTime.getTime();
88
+ await LlmLogService.create({
89
+ data: logEntry,
90
+ props: { isRoot: true },
91
+ });
92
+ throw new BadDataException("Insufficient AI balance. Please recharge your AI balance in Project Settings > Billing.");
93
+ }
94
+ }
95
+ try {
96
+ // Build LLM config
97
+ const llmConfig = {
98
+ llmType: llmProvider.llmType,
99
+ };
100
+ if (llmProvider.apiKey) {
101
+ llmConfig.apiKey = llmProvider.apiKey;
102
+ }
103
+ if (llmProvider.baseUrl) {
104
+ llmConfig.baseUrl = llmProvider.baseUrl.toString();
105
+ }
106
+ if (llmProvider.modelName) {
107
+ llmConfig.modelName = llmProvider.modelName;
108
+ }
109
+ // Execute LLM call
110
+ const response = await LLMService.getCompletion({
111
+ llmProviderConfig: llmConfig,
112
+ messages: request.messages,
113
+ temperature: (_a = request.temperature) !== null && _a !== void 0 ? _a : 0.7,
114
+ });
115
+ const endTime = new Date();
116
+ // Update log with success info
117
+ logEntry.status = LlmLogStatus.Success;
118
+ logEntry.totalTokens = ((_b = response.usage) === null || _b === void 0 ? void 0 : _b.totalTokens) || 0;
119
+ logEntry.responsePreview = response.content.substring(0, 2000); // Store first 2000 chars
120
+ logEntry.requestCompletedAt = endTime;
121
+ logEntry.durationMs = endTime.getTime() - startTime.getTime();
122
+ // Calculate and apply costs if using global provider with billing enabled
123
+ if (shouldBill && response.usage) {
124
+ const totalCost = Math.ceil((response.usage.totalTokens / 1000000) *
125
+ (llmProvider.costPerMillionTokensInUSDCents || 0));
126
+ logEntry.costInUSDCents = totalCost;
127
+ logEntry.wasBilled = true;
128
+ // Deduct from project balance
129
+ if (totalCost > 0) {
130
+ const project = await ProjectService.findOneById({
131
+ id: request.projectId,
132
+ select: { aiCurrentBalanceInUSDCents: true },
133
+ props: { isRoot: true },
134
+ });
135
+ if (project) {
136
+ const newBalance = Math.max(0, (project.aiCurrentBalanceInUSDCents || 0) - totalCost);
137
+ await ProjectService.updateOneById({
138
+ id: request.projectId,
139
+ data: {
140
+ aiCurrentBalanceInUSDCents: newBalance,
141
+ },
142
+ props: { isRoot: true },
143
+ });
144
+ }
145
+ // Check if auto-recharge is needed (do this async, don't wait)
146
+ AIBillingService.rechargeIfBalanceIsLow(request.projectId).catch((err) => {
147
+ logger.error("Error during AI balance auto-recharge check:");
148
+ logger.error(err);
149
+ });
150
+ }
151
+ }
152
+ // Save log entry
153
+ const savedLog = await LlmLogService.create({
154
+ data: logEntry,
155
+ props: { isRoot: true },
156
+ });
157
+ return {
158
+ content: response.content,
159
+ llmLog: savedLog,
160
+ };
161
+ }
162
+ catch (error) {
163
+ // Log the error
164
+ logEntry.status = LlmLogStatus.Error;
165
+ logEntry.statusMessage =
166
+ error instanceof Error ? error.message : String(error);
167
+ logEntry.requestCompletedAt = new Date();
168
+ logEntry.durationMs = new Date().getTime() - startTime.getTime();
169
+ await LlmLogService.create({
170
+ data: logEntry,
171
+ props: { isRoot: true },
172
+ });
173
+ throw error;
174
+ }
175
+ }
176
+ }
177
+ __decorate([
178
+ CaptureSpan(),
179
+ __metadata("design:type", Function),
180
+ __metadata("design:paramtypes", [Object]),
181
+ __metadata("design:returntype", Promise)
182
+ ], Service.prototype, "executeWithLogging", null);
183
+ export default new Service();
184
+ //# sourceMappingURL=AIService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AIService.js","sourceRoot":"","sources":["../../../../Server/Services/AIService.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,WAAW,MAAM,eAAe,CAAC;AACxC,OAAO,kBAAkB,MAAM,sBAAsB,CAAC;AACtD,OAAO,aAAa,MAAM,iBAAiB,CAAC;AAC5C,OAAO,cAAc,MAAM,kBAAkB,CAAC;AAE9C,OAAO,gBAAgB,MAAM,oBAAoB,CAAC;AAClD,OAAO,UAIN,MAAM,yBAAyB,CAAC;AAEjC,OAAO,MAAM,MAAM,oCAAoC,CAAC;AACxD,OAAO,YAAY,MAAM,0BAA0B,CAAC;AAEpD,OAAO,gBAAgB,MAAM,wCAAwC,CAAC;AACtE,OAAO,WAAW,MAAM,gCAAgC,CAAC;AACzD,OAAO,MAAM,MAAM,iBAAiB,CAAC;AAmBrC,MAAM,OAAO,OAAQ,SAAQ,WAAW;IACtC;QACE,KAAK,EAAE,CAAC;IACV,CAAC;IAGY,AAAN,KAAK,CAAC,kBAAkB,CAC7B,OAAqB;;QAErB,MAAM,SAAS,GAAS,IAAI,IAAI,EAAE,CAAC;QAEnC,mCAAmC;QACnC,MAAM,WAAW,GACf,MAAM,kBAAkB,CAAC,wBAAwB,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAEvE,IAAI,CAAC,WAAW,EAAE,CAAC;YACjB,MAAM,IAAI,gBAAgB,CACxB,iHAAiH,CAClH,CAAC;QACJ,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC;YACzB,MAAM,IAAI,gBAAgB,CACxB,+CAA+C,CAChD,CAAC;QACJ,CAAC;QAED,sDAAsD;QACtD,MAAM,QAAQ,GAAW,IAAI,MAAM,EAAE,CAAC;QACtC,Q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C;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,gBAAgB;YAChB,QAAQ,CAAC,MAAM,GAAG,YAAY,CAAC,KAAK,CAAC;YACrC,QAAQ,CAAC,aAAa;gBACpB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACzD,QAAQ,CAAC,kBAAkB,GAAG,IAAI,IAAI,EAAE,CAAC;YACzC,QAAQ,CAAC,UAAU,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,SAAS,CAAC,OAAO,EAAE,CAAC;YAEjE,MAAM,aAAa,CAAC,MAAM,CAAC;gBACzB,IAAI,EAAE,QAAQ;gBACd,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE;aACxB,CAAC,CAAC;YAEH,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF;AAhMc;IADZ,WAAW,EAAE;;;;iDAgMb;AAGH,eAAe,IAAI,OAAO,EAAE,CAAC"}
@@ -0,0 +1,9 @@
1
+ import DatabaseService from "./DatabaseService";
2
+ import Model from "../../Models/DatabaseModels/CodeRepository";
3
+ export class Service extends DatabaseService {
4
+ constructor() {
5
+ super(Model);
6
+ }
7
+ }
8
+ export default new Service();
9
+ //# sourceMappingURL=CodeRepositoryService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CodeRepositoryService.js","sourceRoot":"","sources":["../../../../Server/Services/CodeRepositoryService.ts"],"names":[],"mappings":"AAAA,OAAO,eAAe,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,MAAM,4CAA4C,CAAC;AAE/D,MAAM,OAAO,OAAQ,SAAQ,eAAsB;IACjD;QACE,KAAK,CAAC,KAAK,CAAC,CAAC;IACf,CAAC;CACF;AAED,eAAe,IAAI,OAAO,EAAE,CAAC"}
@@ -50,6 +50,9 @@ import IncidentWorkspaceMessages from "../Utils/Workspace/WorkspaceMessages/Inci
50
50
  import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
51
51
  import MetricType from "../../Models/DatabaseModels/MetricType";
52
52
  import IncidentTemplateService from "./IncidentTemplateService";
53
+ import LLMService from "../Utils/LLM/LLMService";
54
+ import LlmProviderService from "./LlmProviderService";
55
+ import IncidentAIContextBuilder from "../Utils/AI/IncidentAIContextBuilder";
53
56
  export class Service extends DatabaseService {
54
57
  constructor() {
55
58
  super(Model);
@@ -1758,6 +1761,57 @@ ${incidentSeverity.name}
1758
1761
  logger.info(`Updated Incident ${incident.id} current state to ${latestTimeline.incidentStateId}`);
1759
1762
  }
1760
1763
  }
1764
+ async generatePostmortemFromAI(data) {
1765
+ // Get the incident to verify it exists and get the project ID
1766
+ const incident = await this.findOneById({
1767
+ id: data.incidentId,
1768
+ select: {
1769
+ _id: true,
1770
+ projectId: true,
1771
+ },
1772
+ props: {
1773
+ isRoot: true,
1774
+ },
1775
+ });
1776
+ if (!incident || !incident.projectId) {
1777
+ throw new BadDataException("Incident not found");
1778
+ }
1779
+ // Get LLM provider for the project
1780
+ const llmProvider = await LlmProviderService.getLLMProviderForProject(incident.projectId);
1781
+ if (!llmProvider) {
1782
+ throw new BadDataException("No LLM provider configured for this project. Please configure an LLM provider in Settings > AI > LLM Providers.");
1783
+ }
1784
+ if (!llmProvider.llmType) {
1785
+ throw new BadDataException("LLM provider type is not configured properly.");
1786
+ }
1787
+ // Build incident context - always include workspace messages
1788
+ const contextData = await IncidentAIContextBuilder.buildIncidentContext({
1789
+ incidentId: data.incidentId,
1790
+ includeWorkspaceMessages: true,
1791
+ workspaceMessageLimit: 500,
1792
+ });
1793
+ // Format context for postmortem generation
1794
+ const aiContext = IncidentAIContextBuilder.formatIncidentContextForPostmortem(contextData, data.template);
1795
+ // Generate postmortem using LLM
1796
+ const llmConfig = {
1797
+ llmType: llmProvider.llmType,
1798
+ };
1799
+ if (llmProvider.apiKey) {
1800
+ llmConfig.apiKey = llmProvider.apiKey;
1801
+ }
1802
+ if (llmProvider.baseUrl) {
1803
+ llmConfig.baseUrl = llmProvider.baseUrl.toString();
1804
+ }
1805
+ if (llmProvider.modelName) {
1806
+ llmConfig.modelName = llmProvider.modelName;
1807
+ }
1808
+ const response = await LLMService.getCompletion({
1809
+ llmProviderConfig: llmConfig,
1810
+ messages: aiContext.messages,
1811
+ temperature: 0.7,
1812
+ });
1813
+ return response.content;
1814
+ }
1761
1815
  }
1762
1816
  __decorate([
1763
1817
  CaptureSpan(),
@@ -1929,5 +1983,11 @@ __decorate([
1929
1983
  __metadata("design:paramtypes", [Object]),
1930
1984
  __metadata("design:returntype", Promise)
1931
1985
  ], Service.prototype, "getIncidentNumber", null);
1986
+ __decorate([
1987
+ CaptureSpan(),
1988
+ __metadata("design:type", Function),
1989
+ __metadata("design:paramtypes", [Object]),
1990
+ __metadata("design:returntype", Promise)
1991
+ ], Service.prototype, "generatePostmortemFromAI", null);
1932
1992
  export default new Service();
1933
1993
  //# sourceMappingURL=IncidentService.js.map