@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,94 @@
1
+ import Alert from "../../Models/DatabaseModels/Alert";
2
+ import NotFoundException from "../../Types/Exception/NotFoundException";
3
+ import BadDataException from "../../Types/Exception/BadDataException";
4
+ import ObjectID from "../../Types/ObjectID";
5
+ import AlertService from "../Services/AlertService";
6
+ import UserMiddleware from "../Middleware/UserAuthorization";
7
+ import Response from "../Utils/Response";
8
+ import BaseAPI from "./BaseAPI";
9
+ import CommonAPI from "./CommonAPI";
10
+ import AIService from "../Services/AIService";
11
+ import AlertAIContextBuilder from "../Utils/AI/AlertAIContextBuilder";
12
+ import JSONFunctions from "../../Types/JSONFunctions";
13
+ import Permission from "../../Types/Permission";
14
+ export default class AlertAPI extends BaseAPI {
15
+ constructor() {
16
+ var _a;
17
+ super(Alert, AlertService);
18
+ // Generate note from AI
19
+ this.router.post(`${(_a = new this.entityType().getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/generate-note-from-ai/:alertId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
20
+ try {
21
+ await this.generateNoteFromAI(req, res);
22
+ }
23
+ catch (err) {
24
+ next(err);
25
+ }
26
+ });
27
+ }
28
+ async generateNoteFromAI(req, res) {
29
+ var _a;
30
+ const alertIdParam = req.params["alertId"];
31
+ if (!alertIdParam) {
32
+ throw new BadDataException("Alert ID is required");
33
+ }
34
+ let alertId;
35
+ try {
36
+ alertId = new ObjectID(alertIdParam);
37
+ }
38
+ catch (_b) {
39
+ throw new BadDataException("Invalid Alert ID");
40
+ }
41
+ const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
42
+ // Verify user has permission
43
+ const permissions = (_a = props
44
+ .userTenantAccessPermission) === null || _a === void 0 ? void 0 : _a["permissions"];
45
+ const hasPermission = permissions
46
+ ? permissions.some((p) => {
47
+ return (p === Permission.ProjectOwner ||
48
+ p === Permission.ProjectAdmin ||
49
+ p === Permission.EditAlert ||
50
+ p === Permission.CreateAlertInternalNote);
51
+ })
52
+ : false;
53
+ if (!hasPermission && !props.isMasterAdmin) {
54
+ throw new BadDataException("You do not have permission to generate notes for this alert.");
55
+ }
56
+ // Get the template from request body
57
+ const template = JSONFunctions.getJSONValueInPath(req.body, "template");
58
+ // Get the alert to verify it exists and get the project ID
59
+ const alert = await this.service.findOneById({
60
+ id: alertId,
61
+ select: {
62
+ _id: true,
63
+ projectId: true,
64
+ },
65
+ props,
66
+ });
67
+ if (!alert || !alert.projectId) {
68
+ throw new NotFoundException("Alert not found");
69
+ }
70
+ // Build alert context
71
+ const contextData = await AlertAIContextBuilder.buildAlertContext({
72
+ alertId,
73
+ });
74
+ // Format context for note generation
75
+ const aiContext = AlertAIContextBuilder.formatAlertContextForNote(contextData, template);
76
+ // Generate note using AIService (handles billing and logging)
77
+ const aiLogRequest = {
78
+ projectId: alert.projectId,
79
+ feature: "Alert Internal Note",
80
+ alertId: alertId,
81
+ messages: aiContext.messages,
82
+ maxTokens: 4096,
83
+ temperature: 0.7,
84
+ };
85
+ if (props.userId) {
86
+ aiLogRequest.userId = props.userId;
87
+ }
88
+ const response = await AIService.executeWithLogging(aiLogRequest);
89
+ return Response.sendJsonObjectResponse(req, res, {
90
+ note: response.content,
91
+ });
92
+ }
93
+ }
94
+ //# sourceMappingURL=AlertAPI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AlertAPI.js","sourceRoot":"","sources":["../../../../Server/API/AlertAPI.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,mCAAmC,CAAC;AACtD,OAAO,iBAAiB,MAAM,yCAAyC,CAAC;AACxE,OAAO,gBAAgB,MAAM,wCAAwC,CAAC;AACtE,OAAO,QAAQ,MAAM,sBAAsB,CAAC;AAC5C,OAAO,YAEN,MAAM,0BAA0B,CAAC;AAClC,OAAO,cAAc,MAAM,iCAAiC,CAAC;AAC7D,OAAO,QAAQ,MAAM,mBAAmB,CAAC;AACzC,OAAO,OAAO,MAAM,WAAW,CAAC;AAMhC,OAAO,SAAS,MAAM,aAAa,CAAC;AAEpC,OAAO,SAA0C,MAAM,uBAAuB,CAAC;AAC/E,OAAO,qBAGN,MAAM,mCAAmC,CAAC;AAC3C,OAAO,aAAa,MAAM,2BAA2B,CAAC;AACtD,OAAO,UAAU,MAAM,wBAAwB,CAAC;AAEhD,MAAM,CAAC,OAAO,OAAO,QAAS,SAAQ,OAAgC;IACpE;;QACE,KAAK,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;QAE3B,wBAAwB;QACxB,IAAI,CAAC,MAAM,CAAC,IAAI,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kB,CAAC,YAAY,CAAC,CAAC;QAEnD,OAAO,QAAQ,CAAC,sBAAsB,CAAC,GAAG,EAAE,GAAG,EAAE;YAC/C,IAAI,EAAE,QAAQ,CAAC,OAAO;SACvB,CAAC,CAAC;IACL,CAAC;CACF"}
@@ -0,0 +1,207 @@
1
+ import Express from "../Utils/Express";
2
+ import Response from "../Utils/Response";
3
+ import BadDataException from "../../Types/Exception/BadDataException";
4
+ import logger from "../Utils/Logger";
5
+ import { DashboardClientUrl, GitHubAppClientId } from "../EnvironmentConfig";
6
+ import ObjectID from "../../Types/ObjectID";
7
+ import GitHubUtil from "../Utils/CodeRepository/GitHub/GitHub";
8
+ import CodeRepositoryService from "../Services/CodeRepositoryService";
9
+ import CodeRepository from "../../Models/DatabaseModels/CodeRepository";
10
+ import CodeRepositoryType from "../../Types/CodeRepository/CodeRepositoryType";
11
+ import URL from "../../Types/API/URL";
12
+ import UserMiddleware from "../Middleware/UserAuthorization";
13
+ import BaseModel from "../../Models/DatabaseModels/DatabaseBaseModel/DatabaseBaseModel";
14
+ export default class GitHubAPI {
15
+ getRouter() {
16
+ const router = Express.getRouter();
17
+ /*
18
+ * GitHub App installation callback
19
+ * This is called after a user installs the GitHub App
20
+ * The state parameter contains base64 encoded JSON with projectId and userId
21
+ */
22
+ router.get("/github/auth/callback", async (req, res) => {
23
+ var _a, _b;
24
+ try {
25
+ // GitHub sends state parameter back which contains projectId and userId
26
+ const state = (_a = req.query["state"]) === null || _a === void 0 ? void 0 : _a.toString();
27
+ if (!state) {
28
+ return Response.sendErrorResponse(req, res, new BadDataException("State parameter is required"));
29
+ }
30
+ // Decode the state parameter to get projectId and userId
31
+ let projectId;
32
+ let userId;
33
+ try {
34
+ const decodedState = JSON.parse(Buffer.from(state, "base64").toString("utf-8"));
35
+ projectId = decodedState.projectId;
36
+ userId = decodedState.userId;
37
+ }
38
+ catch (_c) {
39
+ return Response.sendErrorResponse(req, res, new BadDataException("Invalid state parameter"));
40
+ }
41
+ if (!projectId) {
42
+ return Response.sendErrorResponse(req, res, new BadDataException("Project ID is required in state"));
43
+ }
44
+ if (!userId) {
45
+ return Response.sendErrorResponse(req, res, new BadDataException("User ID is required in state"));
46
+ }
47
+ // GitHub sends installation_id in query params after app installation
48
+ const installationId = (_b = req.query["installation_id"]) === null || _b === void 0 ? void 0 : _b.toString();
49
+ if (!installationId) {
50
+ return Response.sendErrorResponse(req, res, new BadDataException("Installation ID is required. Please install the GitHub App first."));
51
+ }
52
+ /*
53
+ * Store the installation ID - we'll create repositories when user selects them
54
+ * For now, redirect back to dashboard with installation ID
55
+ */
56
+ const redirectUrl = `${DashboardClientUrl.toString()}/dashboard/${projectId}/code-repository?installation_id=${installationId}`;
57
+ return Response.redirect(req, res, URL.fromString(redirectUrl));
58
+ }
59
+ catch (error) {
60
+ logger.error("GitHub Auth Callback Error:");
61
+ logger.error(error);
62
+ return Response.sendErrorResponse(req, res, error instanceof Error
63
+ ? new BadDataException(error.message)
64
+ : new BadDataException("An error occurred"));
65
+ }
66
+ });
67
+ // Initiate GitHub App installation
68
+ router.get("/github/auth/install", async (req, res) => {
69
+ var _a, _b;
70
+ try {
71
+ if (!GitHubAppClientId) {
72
+ return Response.sendErrorResponse(req, res, new BadDataException("GitHub App is not configured. Please set GITHUB_APP_CLIENT_ID."));
73
+ }
74
+ const projectId = (_a = req.query["projectId"]) === null || _a === void 0 ? void 0 : _a.toString();
75
+ const userId = (_b = req.query["userId"]) === null || _b === void 0 ? void 0 : _b.toString();
76
+ if (!projectId || !userId) {
77
+ return Response.sendErrorResponse(req, res, new BadDataException("Project ID and User ID are required"));
78
+ }
79
+ /*
80
+ * Redirect to GitHub App installation page
81
+ * The state parameter helps us track the installation
82
+ */
83
+ const state = Buffer.from(JSON.stringify({ projectId, userId })).toString("base64");
84
+ const installUrl = `https://github.com/apps/${GitHubAppClientId}/installations/new?state=${state}`;
85
+ return Response.redirect(req, res, URL.fromString(installUrl));
86
+ }
87
+ catch (error) {
88
+ logger.error("GitHub Install Redirect Error:");
89
+ logger.error(error);
90
+ return Response.sendErrorResponse(req, res, error instanceof Error
91
+ ? new BadDataException(error.message)
92
+ : new BadDataException("An error occurred"));
93
+ }
94
+ });
95
+ // List repositories for an installation
96
+ router.get("/github/repositories/:projectId/:installationId", UserMiddleware.getUserMiddleware, async (req, res) => {
97
+ var _a;
98
+ try {
99
+ const installationId = (_a = req.params["installationId"]) === null || _a === void 0 ? void 0 : _a.toString();
100
+ if (!installationId) {
101
+ return Response.sendErrorResponse(req, res, new BadDataException("Installation ID is required"));
102
+ }
103
+ const repositories = await GitHubUtil.listRepositoriesForInstallation(installationId);
104
+ return Response.sendJsonObjectResponse(req, res, {
105
+ repositories: repositories,
106
+ });
107
+ }
108
+ catch (error) {
109
+ logger.error("GitHub List Repositories Error:");
110
+ logger.error(error);
111
+ return Response.sendErrorResponse(req, res, error instanceof Error
112
+ ? new BadDataException(error.message)
113
+ : new BadDataException("An error occurred"));
114
+ }
115
+ });
116
+ // Connect a repository to a project
117
+ router.post("/github/repository/connect", UserMiddleware.getUserMiddleware, async (req, res) => {
118
+ var _a, _b, _c, _d, _e, _f, _g;
119
+ try {
120
+ const body = req.body;
121
+ const projectId = (_a = body["projectId"]) === null || _a === void 0 ? void 0 : _a.toString();
122
+ const installationId = (_b = body["installationId"]) === null || _b === void 0 ? void 0 : _b.toString();
123
+ const repositoryName = (_c = body["repositoryName"]) === null || _c === void 0 ? void 0 : _c.toString();
124
+ const organizationName = (_d = body["organizationName"]) === null || _d === void 0 ? void 0 : _d.toString();
125
+ const name = (_e = body["name"]) === null || _e === void 0 ? void 0 : _e.toString();
126
+ const defaultBranch = (_f = body["defaultBranch"]) === null || _f === void 0 ? void 0 : _f.toString();
127
+ const repositoryUrl = (_g = body["repositoryUrl"]) === null || _g === void 0 ? void 0 : _g.toString();
128
+ if (!projectId) {
129
+ return Response.sendErrorResponse(req, res, new BadDataException("Project ID is required"));
130
+ }
131
+ if (!installationId) {
132
+ return Response.sendErrorResponse(req, res, new BadDataException("Installation ID is required"));
133
+ }
134
+ if (!repositoryName) {
135
+ return Response.sendErrorResponse(req, res, new BadDataException("Repository name is required"));
136
+ }
137
+ if (!organizationName) {
138
+ return Response.sendErrorResponse(req, res, new BadDataException("Organization name is required"));
139
+ }
140
+ // Create the code repository record
141
+ const codeRepository = new CodeRepository();
142
+ codeRepository.projectId = new ObjectID(projectId);
143
+ codeRepository.name = name || `${organizationName}/${repositoryName}`;
144
+ codeRepository.repositoryHostedAt = CodeRepositoryType.GitHub;
145
+ codeRepository.organizationName = organizationName;
146
+ codeRepository.repositoryName = repositoryName;
147
+ codeRepository.mainBranchName = defaultBranch || "main";
148
+ codeRepository.gitHubAppInstallationId = installationId;
149
+ if (repositoryUrl) {
150
+ codeRepository.repositoryUrl = URL.fromString(repositoryUrl);
151
+ }
152
+ const createdRepository = await CodeRepositoryService.create({
153
+ data: codeRepository,
154
+ props: {
155
+ isRoot: true,
156
+ },
157
+ });
158
+ return Response.sendJsonObjectResponse(req, res, {
159
+ repository: BaseModel.toJSON(createdRepository, CodeRepository),
160
+ });
161
+ }
162
+ catch (error) {
163
+ logger.error("GitHub Connect Repository Error:");
164
+ logger.error(error);
165
+ return Response.sendErrorResponse(req, res, error instanceof Error
166
+ ? new BadDataException(error.message)
167
+ : new BadDataException("An error occurred"));
168
+ }
169
+ });
170
+ // GitHub webhook handler
171
+ router.post("/github/webhook", async (req, res) => {
172
+ try {
173
+ const signature = req.headers["x-hub-signature-256"];
174
+ const event = req.headers["x-github-event"];
175
+ if (!signature) {
176
+ return Response.sendErrorResponse(req, res, new BadDataException("Missing webhook signature"));
177
+ }
178
+ // Get raw body for signature verification
179
+ const rawBody = JSON.stringify(req.body);
180
+ // Verify webhook signature
181
+ const isValid = GitHubUtil.verifyWebhookSignature(rawBody, signature);
182
+ if (!isValid) {
183
+ return Response.sendErrorResponse(req, res, new BadDataException("Invalid webhook signature"));
184
+ }
185
+ logger.debug(`Received GitHub webhook event: ${event}`);
186
+ /*
187
+ * Handle different webhook events here
188
+ * For now, just acknowledge receipt
189
+ * Future: Handle push, pull_request, check_run events
190
+ */
191
+ return Response.sendJsonObjectResponse(req, res, {
192
+ success: true,
193
+ message: "Webhook received",
194
+ });
195
+ }
196
+ catch (error) {
197
+ logger.error("GitHub Webhook Error:");
198
+ logger.error(error);
199
+ return Response.sendErrorResponse(req, res, error instanceof Error
200
+ ? new BadDataException(error.message)
201
+ : new BadDataException("An error occurred"));
202
+ }
203
+ });
204
+ return router;
205
+ }
206
+ }
207
+ //# sourceMappingURL=GitHubAPI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GitHubAPI.js","sourceRoot":"","sources":["../../../../Server/API/GitHubAPI.ts"],"names":[],"mappings":"AAAA,OAAO,OAIN,MAAM,kBAAkB,CAAC;AAC1B,OAAO,QAAQ,MAAM,mBAAmB,CAAC;AACzC,OAAO,gBAAgB,MAAM,wCAAwC,CAAC;AACtE,OAAO,MAAM,MAAM,iBAAiB,CAAC;AAErC,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAC7E,OAAO,QAAQ,MAAM,sBAAsB,CAAC;AAC5C,OAAO,UAEN,MAAM,uCAAuC,CAAC;AAC/C,OAAO,qBAAqB,MAAM,mCAAmC,CAAC;AACtE,OAAO,cAAc,MAAM,4CAA4C,CAAC;AACxE,OAAO,kBAAkB,MAAM,+CAA+C,CAAC;AAC/E,OAAO,GAAG,MAAM,qBAAqB,CAAC;AACtC,OAAO,cAAc,MAAM,iCAAiC,CAAC;AAC7D,OAAO,SAAS,MAAM,iEAAiE,CAAC;AAExF,MAAM,CAAC,OAAO,OAAO,SAAS;IACrB,SAAS;QACd,MAAM,MAAM,GAAkB,OAAO,CAAC,SAAS,EAAE,CAAC;QAElD;;;;WAIG;QACH,MAAM,CAAC,GAAG,CACR,uBAAuB,EACvB,KAAK,EAAE,GAAmB,EAAE,GAAoB,EAAE,EAAE;;YAClD,IAAI,CAAC;gBACH,wEAAwE;gBACx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gB,CAAC,2BAA2B,CAAC,CAClD,CAAC;gBACJ,CAAC;gBAED,0CAA0C;gBAC1C,MAAM,OAAO,GAAW,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;gBAEjD,2BAA2B;gBAC3B,MAAM,OAAO,GAAY,UAAU,CAAC,sBAAsB,CACxD,OAAO,EACP,SAAS,CACV,CAAC;gBAEF,IAAI,CAAC,OAAO,EAAE,CAAC;oBACb,OAAO,QAAQ,CAAC,iBAAiB,CAC/B,GAAG,EACH,GAAG,EACH,IAAI,gBAAgB,CAAC,2BAA2B,CAAC,CAClD,CAAC;gBACJ,CAAC;gBAED,MAAM,CAAC,KAAK,CAAC,kCAAkC,KAAK,EAAE,CAAC,CAAC;gBAExD;;;;mBAIG;gBAEH,OAAO,QAAQ,CAAC,sBAAsB,CAAC,GAAG,EAAE,GAAG,EAAE;oBAC/C,OAAO,EAAE,IAAI;oBACb,OAAO,EAAE,kBAAkB;iBACd,CAAC,CAAC;YACnB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;gBACtC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBACpB,OAAO,QAAQ,CAAC,iBAAiB,CAC/B,GAAG,EACH,GAAG,EACH,KAAK,YAAY,KAAK;oBACpB,CAAC,CAAC,IAAI,gBAAgB,CAAC,KAAK,CAAC,OAAO,CAAC;oBACrC,CAAC,CAAC,IAAI,gBAAgB,CAAC,mBAAmB,CAAC,CAC9C,CAAC;YACJ,CAAC;QACH,CAAC,CACF,CAAC;QAEF,OAAO,MAAM,CAAC;IAChB,CAAC;CACF"}
@@ -1,14 +1,19 @@
1
1
  import Incident from "../../Models/DatabaseModels/Incident";
2
2
  import NotFoundException from "../../Types/Exception/NotFoundException";
3
+ import BadDataException from "../../Types/Exception/BadDataException";
3
4
  import ObjectID from "../../Types/ObjectID";
4
5
  import IncidentService from "../Services/IncidentService";
5
6
  import UserMiddleware from "../Middleware/UserAuthorization";
6
7
  import Response from "../Utils/Response";
7
8
  import BaseAPI from "./BaseAPI";
8
9
  import CommonAPI from "./CommonAPI";
10
+ import AIService from "../Services/AIService";
11
+ import IncidentAIContextBuilder from "../Utils/AI/IncidentAIContextBuilder";
12
+ import JSONFunctions from "../../Types/JSONFunctions";
13
+ import Permission from "../../Types/Permission";
9
14
  export default class IncidentAPI extends BaseAPI {
10
15
  constructor() {
11
- var _a;
16
+ var _a, _b, _c;
12
17
  super(Incident, IncidentService);
13
18
  this.router.get(`${(_a = new this.entityType()
14
19
  .getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/postmortem/attachment/:projectId/:incidentId/:fileId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
@@ -19,6 +24,26 @@ export default class IncidentAPI extends BaseAPI {
19
24
  next(err);
20
25
  }
21
26
  });
27
+ // Generate postmortem from AI
28
+ this.router.post(`${(_b = new this.entityType()
29
+ .getCrudApiPath()) === null || _b === void 0 ? void 0 : _b.toString()}/generate-postmortem-from-ai/:incidentId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
30
+ try {
31
+ await this.generatePostmortemFromAI(req, res);
32
+ }
33
+ catch (err) {
34
+ next(err);
35
+ }
36
+ });
37
+ // Generate note from AI
38
+ this.router.post(`${(_c = new this.entityType()
39
+ .getCrudApiPath()) === null || _c === void 0 ? void 0 : _c.toString()}/generate-note-from-ai/:incidentId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
40
+ try {
41
+ await this.generateNoteFromAI(req, res);
42
+ }
43
+ catch (err) {
44
+ next(err);
45
+ }
46
+ });
22
47
  }
23
48
  async getPostmortemAttachment(req, res) {
24
49
  var _a;
@@ -72,5 +97,150 @@ export default class IncidentAPI extends BaseAPI {
72
97
  Response.setNoCacheHeaders(res);
73
98
  return Response.sendFileResponse(req, res, attachment);
74
99
  }
100
+ async generatePostmortemFromAI(req, res) {
101
+ var _a;
102
+ const incidentIdParam = req.params["incidentId"];
103
+ if (!incidentIdParam) {
104
+ throw new BadDataException("Incident ID is required");
105
+ }
106
+ let incidentId;
107
+ try {
108
+ incidentId = new ObjectID(incidentIdParam);
109
+ }
110
+ catch (_b) {
111
+ throw new BadDataException("Invalid Incident ID");
112
+ }
113
+ const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
114
+ // Verify user has permission to edit the incident
115
+ const permissions = (_a = props
116
+ .userTenantAccessPermission) === null || _a === void 0 ? void 0 : _a["permissions"];
117
+ const hasPermission = permissions
118
+ ? permissions.some((p) => {
119
+ return (p === Permission.ProjectOwner ||
120
+ p === Permission.ProjectAdmin ||
121
+ p === Permission.EditProjectIncident);
122
+ })
123
+ : false;
124
+ if (!hasPermission && !props.isMasterAdmin) {
125
+ throw new BadDataException("You do not have permission to generate postmortem for this incident. You need to have one of these permissions: Project Owner, Project Admin, Edit Project Incident.");
126
+ }
127
+ // Get the template from request body if provided
128
+ const template = JSONFunctions.getJSONValueInPath(req.body, "template");
129
+ // Always include workspace messages for comprehensive context
130
+ const includeWorkspaceMessages = true;
131
+ // Get the incident to verify it exists and get the project ID
132
+ const incident = await this.service.findOneById({
133
+ id: incidentId,
134
+ select: {
135
+ _id: true,
136
+ projectId: true,
137
+ },
138
+ props,
139
+ });
140
+ if (!incident || !incident.projectId) {
141
+ throw new NotFoundException("Incident not found");
142
+ }
143
+ // Build incident context
144
+ const contextData = await IncidentAIContextBuilder.buildIncidentContext({
145
+ incidentId,
146
+ includeWorkspaceMessages,
147
+ workspaceMessageLimit: 500,
148
+ });
149
+ // Format context for postmortem generation
150
+ const aiContext = IncidentAIContextBuilder.formatIncidentContextForPostmortem(contextData, template);
151
+ // Generate postmortem using AIService (handles billing and logging)
152
+ const aiLogRequest = {
153
+ projectId: incident.projectId,
154
+ feature: "Incident Postmortem",
155
+ incidentId: incidentId,
156
+ messages: aiContext.messages,
157
+ maxTokens: 8192,
158
+ temperature: 0.7,
159
+ };
160
+ if (props.userId) {
161
+ aiLogRequest.userId = props.userId;
162
+ }
163
+ const response = await AIService.executeWithLogging(aiLogRequest);
164
+ return Response.sendJsonObjectResponse(req, res, {
165
+ postmortemNote: response.content,
166
+ });
167
+ }
168
+ async generateNoteFromAI(req, res) {
169
+ var _a;
170
+ const incidentIdParam = req.params["incidentId"];
171
+ if (!incidentIdParam) {
172
+ throw new BadDataException("Incident ID is required");
173
+ }
174
+ let incidentId;
175
+ try {
176
+ incidentId = new ObjectID(incidentIdParam);
177
+ }
178
+ catch (_b) {
179
+ throw new BadDataException("Invalid Incident ID");
180
+ }
181
+ const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
182
+ // Verify user has permission to edit the incident
183
+ const permissions = (_a = props
184
+ .userTenantAccessPermission) === null || _a === void 0 ? void 0 : _a["permissions"];
185
+ const hasPermission = permissions
186
+ ? permissions.some((p) => {
187
+ return (p === Permission.ProjectOwner ||
188
+ p === Permission.ProjectAdmin ||
189
+ p === Permission.EditProjectIncident ||
190
+ p === Permission.CreateIncidentInternalNote ||
191
+ p === Permission.CreateIncidentPublicNote);
192
+ })
193
+ : false;
194
+ if (!hasPermission && !props.isMasterAdmin) {
195
+ throw new BadDataException("You do not have permission to generate notes for this incident.");
196
+ }
197
+ // Get the template and note type from request body
198
+ const template = JSONFunctions.getJSONValueInPath(req.body, "template");
199
+ const noteType = JSONFunctions.getJSONValueInPath(req.body, "noteType") ||
200
+ "internal";
201
+ if (noteType !== "public" && noteType !== "internal") {
202
+ throw new BadDataException("Note type must be 'public' or 'internal'");
203
+ }
204
+ // Always include workspace messages for comprehensive context
205
+ const includeWorkspaceMessages = true;
206
+ // Get the incident to verify it exists and get the project ID
207
+ const incident = await this.service.findOneById({
208
+ id: incidentId,
209
+ select: {
210
+ _id: true,
211
+ projectId: true,
212
+ },
213
+ props,
214
+ });
215
+ if (!incident || !incident.projectId) {
216
+ throw new NotFoundException("Incident not found");
217
+ }
218
+ // Build incident context
219
+ const contextData = await IncidentAIContextBuilder.buildIncidentContext({
220
+ incidentId,
221
+ includeWorkspaceMessages,
222
+ workspaceMessageLimit: 300,
223
+ });
224
+ // Format context for note generation
225
+ const aiContext = IncidentAIContextBuilder.formatIncidentContextForNote(contextData, noteType, template);
226
+ // Generate note using AIService (handles billing and logging)
227
+ const aiLogRequest = {
228
+ projectId: incident.projectId,
229
+ feature: noteType === "public"
230
+ ? "Incident Public Note"
231
+ : "Incident Internal Note",
232
+ incidentId: incidentId,
233
+ messages: aiContext.messages,
234
+ maxTokens: 4096,
235
+ temperature: 0.7,
236
+ };
237
+ if (props.userId) {
238
+ aiLogRequest.userId = props.userId;
239
+ }
240
+ const response = await AIService.executeWithLogging(aiLogRequest);
241
+ return Response.sendJsonObjectResponse(req, res, {
242
+ note: response.content,
243
+ });
244
+ }
75
245
  }
76
246
  //# sourceMappingURL=IncidentAPI.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"IncidentAPI.js","sourceRoot":"","sources":["../../../../Server/API/IncidentAPI.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,sCAAsC,CAAC;AAE5D,OAAO,iBAAiB,MAAM,yCAAyC,CAAC;AACxE,OAAO,QAAQ,MAAM,sBAAsB,CAAC;AAC5C,OAAO,eAEN,MAAM,6BAA6B,CAAC;AACrC,OAAO,cAAc,MAAM,iCAAiC,CAAC;AAC7D,OAAO,QAAQ,MAAM,mBAAmB,CAAC;AACzC,OAAO,OAAO,MAAM,WAAW,CAAC;AAMhC,OAAO,SAAS,MAAM,aAAa,CAAC;AAGpC,MAAM,CAAC,OAAO,OAAO,WAAY,SAAQ,OAGxC;IACC;;QACE,KAAK,CAAC,QAAQ,EAAE,eAAe,CAAC,CAAC;QAEjC,IAAI,CAAC,MAAM,CAAC,GAAG,CACb,GAAG,MAAA,IAAI,IAAI,CAAC,UAAU,EAAE;aACrB,cAAc,EAAE,0CACf,QAAQ,EAAE,uDAAuD,EACrE,cAAc,CAAC,iBAAiB,EAChC,KAAK,EAAE,GAAmB,EAAE,GAAoB,EAAE,IAAkB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import NotFoundException from "../../Types/Exception/NotFoundException";
3
+ import BadDataException from "../../Types/Exception/BadDataException";
4
+ import ObjectID from "../../Types/ObjectID";
5
+ import ScheduledMaintenanceService from "../Services/ScheduledMaintenanceService";
6
+ import UserMiddleware from "../Middleware/UserAuthorization";
7
+ import Response from "../Utils/Response";
8
+ import BaseAPI from "./BaseAPI";
9
+ import CommonAPI from "./CommonAPI";
10
+ import AIService from "../Services/AIService";
11
+ import ScheduledMaintenanceAIContextBuilder from "../Utils/AI/ScheduledMaintenanceAIContextBuilder";
12
+ import JSONFunctions from "../../Types/JSONFunctions";
13
+ import Permission from "../../Types/Permission";
14
+ export default class ScheduledMaintenanceAPI extends BaseAPI {
15
+ constructor() {
16
+ var _a;
17
+ super(ScheduledMaintenance, ScheduledMaintenanceService);
18
+ // Generate note from AI
19
+ this.router.post(`${(_a = new this.entityType()
20
+ .getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/generate-note-from-ai/:scheduledMaintenanceId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
21
+ try {
22
+ await this.generateNoteFromAI(req, res);
23
+ }
24
+ catch (err) {
25
+ next(err);
26
+ }
27
+ });
28
+ }
29
+ async generateNoteFromAI(req, res) {
30
+ var _a;
31
+ const scheduledMaintenanceIdParam = req.params["scheduledMaintenanceId"];
32
+ if (!scheduledMaintenanceIdParam) {
33
+ throw new BadDataException("Scheduled Maintenance ID is required");
34
+ }
35
+ let scheduledMaintenanceId;
36
+ try {
37
+ scheduledMaintenanceId = new ObjectID(scheduledMaintenanceIdParam);
38
+ }
39
+ catch (_b) {
40
+ throw new BadDataException("Invalid Scheduled Maintenance ID");
41
+ }
42
+ const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
43
+ // Verify user has permission
44
+ const permissions = (_a = props
45
+ .userTenantAccessPermission) === null || _a === void 0 ? void 0 : _a["permissions"];
46
+ const hasPermission = permissions
47
+ ? permissions.some((p) => {
48
+ return (p === Permission.ProjectOwner ||
49
+ p === Permission.ProjectAdmin ||
50
+ p === Permission.EditProjectScheduledMaintenance ||
51
+ p === Permission.CreateScheduledMaintenanceInternalNote ||
52
+ p === Permission.CreateScheduledMaintenancePublicNote);
53
+ })
54
+ : false;
55
+ if (!hasPermission && !props.isMasterAdmin) {
56
+ throw new BadDataException("You do not have permission to generate notes for this scheduled maintenance.");
57
+ }
58
+ // Get the template and note type from request body
59
+ const template = JSONFunctions.getJSONValueInPath(req.body, "template");
60
+ const noteType = JSONFunctions.getJSONValueInPath(req.body, "noteType") ||
61
+ "internal";
62
+ if (noteType !== "public" && noteType !== "internal") {
63
+ throw new BadDataException("Note type must be 'public' or 'internal'");
64
+ }
65
+ // Get the scheduled maintenance to verify it exists and get the project ID
66
+ const scheduledMaintenance = await this.service.findOneById({
67
+ id: scheduledMaintenanceId,
68
+ select: {
69
+ _id: true,
70
+ projectId: true,
71
+ },
72
+ props,
73
+ });
74
+ if (!scheduledMaintenance || !scheduledMaintenance.projectId) {
75
+ throw new NotFoundException("Scheduled Maintenance not found");
76
+ }
77
+ // Build scheduled maintenance context
78
+ const contextData = await ScheduledMaintenanceAIContextBuilder.buildScheduledMaintenanceContext({
79
+ scheduledMaintenanceId,
80
+ });
81
+ // Format context for note generation
82
+ const aiContext = ScheduledMaintenanceAIContextBuilder.formatScheduledMaintenanceContextForNote(contextData, noteType, template);
83
+ // Generate note using AIService (handles billing and logging)
84
+ const aiLogRequest = {
85
+ projectId: scheduledMaintenance.projectId,
86
+ feature: noteType === "public"
87
+ ? "Scheduled Maintenance Public Note"
88
+ : "Scheduled Maintenance Internal Note",
89
+ scheduledMaintenanceId: scheduledMaintenanceId,
90
+ messages: aiContext.messages,
91
+ maxTokens: 4096,
92
+ temperature: 0.7,
93
+ };
94
+ if (props.userId) {
95
+ aiLogRequest.userId = props.userId;
96
+ }
97
+ const response = await AIService.executeWithLogging(aiLogRequest);
98
+ return Response.sendJsonObjectResponse(req, res, {
99
+ note: response.content,
100
+ });
101
+ }
102
+ }
103
+ //# sourceMappingURL=ScheduledMaintenanceAPI.js.map