@mastra/factory 0.2.2-alpha.1 → 0.2.2-alpha.2

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 (155) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/auth.js +401 -334
  3. package/dist/auth.js.map +1 -1
  4. package/dist/capabilities/connection.js +1 -1
  5. package/dist/capabilities/intake.js +1 -1
  6. package/dist/capabilities/version-control.js +1 -1
  7. package/dist/factory.js +441 -39622
  8. package/dist/factory.js.map +1 -1
  9. package/dist/index.js +2 -39633
  10. package/dist/integrations/base.js +1 -1
  11. package/dist/integrations/github/config.js +36 -22
  12. package/dist/integrations/github/config.js.map +1 -1
  13. package/dist/integrations/github/factory-session.js +33 -37
  14. package/dist/integrations/github/factory-session.js.map +1 -1
  15. package/dist/integrations/github/integration.js +1037 -3672
  16. package/dist/integrations/github/integration.js.map +1 -1
  17. package/dist/integrations/github/issue-triage.js +71 -71
  18. package/dist/integrations/github/issue-triage.js.map +1 -1
  19. package/dist/integrations/github/pat.js +47 -36
  20. package/dist/integrations/github/pat.js.map +1 -1
  21. package/dist/integrations/github/provenance.js +72 -101
  22. package/dist/integrations/github/provenance.js.map +1 -1
  23. package/dist/integrations/github/routes.js +1272 -1881
  24. package/dist/integrations/github/routes.js.map +1 -1
  25. package/dist/integrations/github/rules.js +203 -471
  26. package/dist/integrations/github/rules.js.map +1 -1
  27. package/dist/integrations/github/sandbox.js +400 -345
  28. package/dist/integrations/github/sandbox.js.map +1 -1
  29. package/dist/integrations/github/session-subscriptions.js +165 -223
  30. package/dist/integrations/github/session-subscriptions.js.map +1 -1
  31. package/dist/integrations/github/subscriptions.js +43 -51
  32. package/dist/integrations/github/subscriptions.js.map +1 -1
  33. package/dist/integrations/github/token-refresh.js +15 -18
  34. package/dist/integrations/github/token-refresh.js.map +1 -1
  35. package/dist/integrations/github/webhook.js +359 -343
  36. package/dist/integrations/github/webhook.js.map +1 -1
  37. package/dist/integrations/linear/agent-tools.js +77 -100
  38. package/dist/integrations/linear/agent-tools.js.map +1 -1
  39. package/dist/integrations/linear/integration.js +611 -1309
  40. package/dist/integrations/linear/integration.js.map +1 -1
  41. package/dist/integrations/linear/routes.js +227 -230
  42. package/dist/integrations/linear/routes.js.map +1 -1
  43. package/dist/integrations/linear/rules.js +126 -346
  44. package/dist/integrations/linear/rules.js.map +1 -1
  45. package/dist/integrations/linear/storage.js +1 -1
  46. package/dist/integrations/platform/api-client.js +131 -135
  47. package/dist/integrations/platform/api-client.js.map +1 -1
  48. package/dist/integrations/platform/github/event-worker.js +275 -573
  49. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  50. package/dist/integrations/platform/github/integration.js +845 -4022
  51. package/dist/integrations/platform/github/integration.js.map +1 -1
  52. package/dist/integrations/platform/linear/integration.js +457 -1309
  53. package/dist/integrations/platform/linear/integration.js.map +1 -1
  54. package/dist/integrations/workos/integration.js +80 -85
  55. package/dist/integrations/workos/integration.js.map +1 -1
  56. package/dist/routes/config.d.ts.map +1 -1
  57. package/dist/routes/config.js +933 -912
  58. package/dist/routes/config.js.map +1 -1
  59. package/dist/routes/custom-provider-source.js +110 -93
  60. package/dist/routes/custom-provider-source.js.map +1 -1
  61. package/dist/routes/fs.js +401 -349
  62. package/dist/routes/fs.js.map +1 -1
  63. package/dist/routes/intake.js +165 -165
  64. package/dist/routes/intake.js.map +1 -1
  65. package/dist/routes/oauth.js +447 -25166
  66. package/dist/routes/oauth.js.map +1 -1
  67. package/dist/routes/projects.js +437 -376
  68. package/dist/routes/projects.js.map +1 -1
  69. package/dist/routes/provider-credentials.js +76 -58
  70. package/dist/routes/provider-credentials.js.map +1 -1
  71. package/dist/routes/route.js +12 -8
  72. package/dist/routes/route.js.map +1 -1
  73. package/dist/routes/skills.js +160 -173
  74. package/dist/routes/skills.js.map +1 -1
  75. package/dist/routes/surface.js +250 -28615
  76. package/dist/routes/surface.js.map +1 -1
  77. package/dist/routes/tenant-credentials.js +141 -166
  78. package/dist/routes/tenant-credentials.js.map +1 -1
  79. package/dist/routes/work-items.js +654 -862
  80. package/dist/routes/work-items.js.map +1 -1
  81. package/dist/rules/binding-context.js +23 -35
  82. package/dist/rules/binding-context.js.map +1 -1
  83. package/dist/rules/defaults.js +200 -309
  84. package/dist/rules/defaults.js.map +1 -1
  85. package/dist/rules/dispatcher.js +438 -683
  86. package/dist/rules/dispatcher.js.map +1 -1
  87. package/dist/rules/index.js +5 -599
  88. package/dist/rules/processor.js +344 -596
  89. package/dist/rules/processor.js.map +1 -1
  90. package/dist/rules/resolve.js +21 -18
  91. package/dist/rules/resolve.js.map +1 -1
  92. package/dist/rules/start-coordinator.js +168 -157
  93. package/dist/rules/start-coordinator.js.map +1 -1
  94. package/dist/rules/tools.js +50 -85
  95. package/dist/rules/tools.js.map +1 -1
  96. package/dist/rules/transition-service.js +183 -454
  97. package/dist/rules/transition-service.js.map +1 -1
  98. package/dist/rules/types.js +33 -29
  99. package/dist/rules/types.js.map +1 -1
  100. package/dist/rules/validation.js +266 -281
  101. package/dist/rules/validation.js.map +1 -1
  102. package/dist/sandbox/fleet.js +272 -250
  103. package/dist/sandbox/fleet.js.map +1 -1
  104. package/dist/sandbox/reattach.js +13 -6
  105. package/dist/sandbox/reattach.js.map +1 -1
  106. package/dist/server-error.js +12 -16
  107. package/dist/server-error.js.map +1 -1
  108. package/dist/skills/service.js +30 -35
  109. package/dist/skills/service.js.map +1 -1
  110. package/dist/spa-static.js +91 -65
  111. package/dist/spa-static.js.map +1 -1
  112. package/dist/state-signing.js +73 -44
  113. package/dist/state-signing.js.map +1 -1
  114. package/dist/storage/domains/audit/agent-audit.js +60 -59
  115. package/dist/storage/domains/audit/agent-audit.js.map +1 -1
  116. package/dist/storage/domains/audit/base.js +169 -112
  117. package/dist/storage/domains/audit/base.js.map +1 -1
  118. package/dist/storage/domains/audit/domain.js +155 -153
  119. package/dist/storage/domains/audit/domain.js.map +1 -1
  120. package/dist/storage/domains/credentials/base.js +259 -243
  121. package/dist/storage/domains/credentials/base.js.map +1 -1
  122. package/dist/storage/domains/custom-providers/base.js +138 -143
  123. package/dist/storage/domains/custom-providers/base.js.map +1 -1
  124. package/dist/storage/domains/intake/base.js +75 -57
  125. package/dist/storage/domains/intake/base.js.map +1 -1
  126. package/dist/storage/domains/integrations/base.js +310 -245
  127. package/dist/storage/domains/integrations/base.js.map +1 -1
  128. package/dist/storage/domains/memory-settings/base.js +117 -102
  129. package/dist/storage/domains/memory-settings/base.js.map +1 -1
  130. package/dist/storage/domains/model-packs/base.js +89 -88
  131. package/dist/storage/domains/model-packs/base.js.map +1 -1
  132. package/dist/storage/domains/projects/base.js +97 -92
  133. package/dist/storage/domains/projects/base.js.map +1 -1
  134. package/dist/storage/domains/queue-health/base.js +111 -76
  135. package/dist/storage/domains/queue-health/base.js.map +1 -1
  136. package/dist/storage/domains/source-control/base.js +777 -706
  137. package/dist/storage/domains/source-control/base.js.map +1 -1
  138. package/dist/storage/domains/source-control/inmemory.js +322 -348
  139. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  140. package/dist/storage/domains/work-items/base.js +1266 -1148
  141. package/dist/storage/domains/work-items/base.js.map +1 -1
  142. package/dist/storage/domains/work-items/metrics.js +202 -184
  143. package/dist/storage/domains/work-items/metrics.js.map +1 -1
  144. package/dist/timing.js +29 -22
  145. package/dist/timing.js.map +1 -1
  146. package/dist/workspace.js +236 -477
  147. package/dist/workspace.js.map +1 -1
  148. package/package.json +8 -8
  149. package/dist/capabilities/connection.js.map +0 -1
  150. package/dist/capabilities/intake.js.map +0 -1
  151. package/dist/capabilities/version-control.js.map +0 -1
  152. package/dist/index.js.map +0 -1
  153. package/dist/integrations/base.js.map +0 -1
  154. package/dist/integrations/linear/storage.js.map +0 -1
  155. package/dist/rules/index.js.map +0 -1
@@ -1,4069 +1,892 @@
1
- // src/integrations/platform/github/integration.ts
2
- import { registerApiRoute as registerApiRoute2 } from "@mastra/core/server";
3
-
4
- // src/integrations/github/routes.ts
5
- import { randomUUID } from "crypto";
1
+ import { createGithubSubscriptionTools, parseCreatedPullRequest, subscribeCurrentSessionToPullRequest } from "../../github/session-subscriptions.js";
2
+ import { buildGithubRoutes } from "../../github/routes.js";
3
+ import { attachGithubRules } from "../../github/rules.js";
4
+ import { PlatformApiClient, PlatformApiError, logPlatformInfo, logPlatformWarn, platformApiClientConfigFromEnv } from "../api-client.js";
5
+ import { PlatformGithubEventWorker } from "./event-worker.js";
6
6
  import { registerApiRoute } from "@mastra/core/server";
7
- import { streamSSE } from "hono/streaming";
8
-
9
- // src/sandbox/fleet.ts
10
- import path from "path";
11
- function reportProgress(onProgress, event) {
12
- if (!onProgress) return;
13
- try {
14
- onProgress(event);
15
- } catch {
16
- }
17
- }
18
- var SandboxBudgetError = class extends Error {
19
- constructor(max) {
20
- super(
21
- `Sandbox budget exceeded: this server already has ${max} active sandbox(es), the configured per-replica maximum. Close an existing repository's sandbox and try again.`
22
- );
23
- this.max = max;
24
- this.name = "SandboxBudgetError";
25
- }
26
- max;
27
- code = "sandbox-budget-exceeded";
28
- };
29
-
30
- // src/integrations/github/config.ts
31
- var GITHUB_APP_ENV_VARS = [
32
- "GITHUB_APP_ID",
33
- "GITHUB_APP_PRIVATE_KEY",
34
- "GITHUB_APP_CLIENT_ID",
35
- "GITHUB_APP_CLIENT_SECRET",
36
- "GITHUB_APP_SLUG"
37
- ];
38
- function isGithubFeatureEnabled(options) {
39
- return options.github !== void 0 && options.auth.enabled();
40
- }
41
- function getGithubFeatureDiagnostics(options) {
42
- const { github, auth, appDbConfigured, stateSigner, fleet } = options;
43
- return {
44
- githubAppConfigured: github !== void 0,
45
- factoryAuthEnabled: auth.enabled(),
46
- appDbConfigured,
47
- stateSecretConfigured: stateSigner?.stable ?? false,
48
- sandboxEnabled: fleet?.enabled ?? false,
49
- sandboxProvider: fleet?.provider ?? "none",
50
- missingGithubAppEnvVars: github ? [] : [...GITHUB_APP_ENV_VARS]
51
- };
52
- }
53
-
54
- // src/integrations/github/pat.ts
55
- var PAT_SETTINGS_USER_ID = "__github_org_settings__";
56
- var FIELD_FOR_KIND = {
57
- default: "pat",
58
- reviewer: "reviewerPat"
59
- };
60
- function asToken(value) {
61
- return typeof value === "string" && value.length > 0 ? value : null;
62
- }
63
- async function getGithubPat(getStorage, orgId, kind = "default") {
64
- try {
65
- const settings = await getStorage().settings.get(orgId, PAT_SETTINGS_USER_ID);
66
- if (!settings) return null;
67
- if (kind === "reviewer") return asToken(settings.reviewerPat) ?? asToken(settings.pat);
68
- return asToken(settings.pat);
69
- } catch {
70
- return null;
71
- }
72
- }
73
- async function getGithubPatStatus(getStorage, orgId) {
74
- try {
75
- const settings = await getStorage().settings.get(orgId, PAT_SETTINGS_USER_ID);
76
- return {
77
- configured: asToken(settings?.pat) !== null,
78
- reviewerConfigured: asToken(settings?.reviewerPat) !== null
79
- };
80
- } catch {
81
- return { configured: false, reviewerConfigured: false };
82
- }
83
- }
84
- async function setGithubPat(storage, orgId, pat, kind = "default") {
85
- const existing = await storage.settings.get(orgId, PAT_SETTINGS_USER_ID) ?? {};
86
- await storage.settings.save(orgId, PAT_SETTINGS_USER_ID, { ...existing, [FIELD_FOR_KIND[kind]]: pat });
87
- }
88
- async function clearGithubPat(storage, orgId, kind = "default") {
89
- const existing = await storage.settings.get(orgId, PAT_SETTINGS_USER_ID);
90
- const field = FIELD_FOR_KIND[kind];
91
- if (!existing?.[field]) return;
92
- const { [field]: _removed, ...rest } = existing;
93
- await storage.settings.save(orgId, PAT_SETTINGS_USER_ID, rest);
94
- }
95
-
96
- // src/integrations/github/sandbox.ts
97
- import { createHash } from "crypto";
98
- function bindingStore(row, storage) {
99
- return {
100
- sandboxId: row.sandboxId,
101
- setSandboxId: (id) => id === null ? storage.clearBinding({ id: row.id }) : storage.setSandboxId({ id: row.id, sandboxId: id }),
102
- clear: () => storage.clearBinding({ id: row.id })
103
- };
104
- }
105
- async function ensureProjectSandbox(options) {
106
- const { fleet, row, storage, token, onProgress } = options;
107
- return fleet.ensureSandbox(bindingStore(row, storage), { GH_TOKEN: token }, onProgress);
108
- }
109
- async function teardownProjectSandbox(options) {
110
- const { fleet, row, storage, sandbox } = options;
111
- return fleet.teardownSandbox(bindingStore(row, storage), sandbox);
112
- }
113
- function shellQuote(value) {
114
- return `'` + value.split(`'`).join(`'\\''`) + `'`;
115
- }
116
- var DEFAULT_COMMAND_TIMEOUT_MS = 15 * 6e4;
117
- var CHECKOUT_COMMAND_TIMEOUT_MS = 5 * 6e4;
118
- async function sh(sandbox, script, options = {}) {
119
- const timeoutMs = options.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
120
- let timer;
121
- const hangGuard = new Promise((_, reject) => {
122
- timer = setTimeout(() => {
123
- const phase = options.phase ? ` during ${options.phase}` : "";
124
- reject(new Error(`Sandbox command timed out after ${Math.round(timeoutMs / 1e3)}s${phase}.`));
125
- }, timeoutMs);
126
- timer.unref?.();
127
- });
128
- try {
129
- return await Promise.race([sandbox.executeCommand("sh", ["-c", script], { timeout: timeoutMs }), hangGuard]);
130
- } finally {
131
- clearTimeout(timer);
132
- }
133
- }
134
- var MaterializeError = class extends Error {
135
- constructor(message, code) {
136
- super(message);
137
- this.code = code;
138
- this.name = "MaterializeError";
139
- }
140
- code;
141
- };
142
- function tokenUrl(repoFullName, token) {
143
- return `https://x-access-token:${token}@github.com/${repoFullName}.git`;
144
- }
145
- function cleanUrl(repoFullName) {
146
- return `https://github.com/${repoFullName}.git`;
147
- }
148
- async function materializeRepo(options) {
149
- const { row: sandboxRow, repoInfo, sandbox, token, storage, onProgress } = options;
150
- const workdir = sandboxRow.sandboxWorkdir;
151
- const repo = repoInfo.repoFullName;
152
- if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) {
153
- throw new MaterializeError(`Refusing to materialize: invalid repo full name '${repo}'.`, "clone-failed");
154
- }
155
- if (!/^[A-Za-z0-9_./-]+$/.test(repoInfo.defaultBranch)) {
156
- throw new MaterializeError(
157
- `Refusing to materialize: invalid default branch '${repoInfo.defaultBranch}'.`,
158
- "clone-failed"
159
- );
160
- }
161
- const gitVersion = await sh(sandbox, "git --version");
162
- if (gitVersion.exitCode !== 0) {
163
- throw new MaterializeError(
164
- "git is not installed in the sandbox. The sandbox template must include git.",
165
- "git-missing"
166
- );
167
- }
168
- const authUrl = tokenUrl(repo, token);
169
- const alreadyMaterialized = await hasExistingCheckout(sandbox, workdir, repo);
170
- let succeeded = false;
171
- try {
172
- if (!alreadyMaterialized) {
173
- reportProgress(onProgress, {
174
- phase: "cloning",
175
- message: `Cloning ${repo} (first open can take a minute)\u2026`
176
- });
177
- const clone = await sh(
178
- sandbox,
179
- `git clone --depth=1 --single-branch --branch ${shellQuote(repoInfo.defaultBranch)} ${shellQuote(authUrl)} ${shellQuote(workdir)}`,
180
- { phase: "repository clone" }
181
- );
182
- if (clone.exitCode !== 0) {
183
- throw classifyGitFailure(clone, "clone-failed");
184
- }
185
- } else {
186
- reportProgress(onProgress, { phase: "pulling", message: `Updating ${repo} to the latest changes\u2026` });
187
- const setUrl = await sh(sandbox, `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(authUrl)}`);
188
- if (setUrl.exitCode !== 0) {
189
- throw new MaterializeError(`Failed to set git remote: ${setUrl.stderr}`, "pull-failed");
190
- }
191
- const pull = await sh(sandbox, `git -C ${shellQuote(workdir)} pull --ff-only`, { phase: "repository pull" });
192
- if (pull.exitCode !== 0) {
193
- throw classifyGitFailure(pull, "pull-failed");
194
- }
195
- }
196
- succeeded = true;
197
- } finally {
198
- await scrubRemote(sandbox, workdir, repo, succeeded);
199
- }
200
- reportProgress(onProgress, { phase: "finalizing", message: "Finalizing workspace\u2026" });
201
- await storage.markMaterialized({ id: sandboxRow.id });
202
- }
203
- async function hasExistingCheckout(sandbox, workdir, repoFullName) {
204
- const result = await sh(sandbox, `git -C ${shellQuote(workdir)} remote get-url origin`);
205
- if (result.exitCode !== 0) return false;
206
- const url = result.stdout.trim().toLowerCase();
207
- const suffix = `github.com/${repoFullName.toLowerCase()}`;
208
- return url.endsWith(`${suffix}.git`) || url.endsWith(suffix);
209
- }
210
- async function scrubRemote(sandbox, workdir, repoFullName, expectGitDir) {
211
- const result = await sh(
212
- sandbox,
213
- `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(cleanUrl(repoFullName))}`
214
- );
215
- if (result.exitCode !== 0 && expectGitDir) {
216
- throw new MaterializeError(
217
- `Failed to scrub installation token from git remote: ${result.stderr.trim() || result.stdout.trim()}`,
218
- "pull-failed"
219
- );
220
- }
221
- }
222
- function classifyGitFailure(result, fallback) {
223
- const stderr = result.stderr || "";
224
- if (/could not resolve host|failed to connect|network is unreachable|Connection timed out/i.test(stderr)) {
225
- return new MaterializeError(
226
- "The sandbox could not reach github.com. The sandbox network must allow outbound egress to github.com.",
227
- "egress-blocked"
228
- );
229
- }
230
- const verb = fallback === "clone-failed" ? "clone" : fallback === "pull-failed" ? "pull" : "push";
231
- return new MaterializeError(`git ${verb} failed: ${stderr}`, fallback);
232
- }
233
- function isValidGitRef(value) {
234
- return typeof value === "string" && value.length > 0 && value.length <= 255 && // Reject leading-dash refs (e.g. `--mirror`) so the value can never be
235
- // parsed as a git option when interpolated into a command.
236
- !value.startsWith("-") && /^[A-Za-z0-9_./-]+$/.test(value);
237
- }
238
- function resolveGitIdentity(identity) {
239
- const login = (identity.login || "").trim();
240
- const name = (identity.name || "").trim() || login || "Mastra Code";
241
- const email = (identity.email || "").trim() || (login ? `${login}@users.noreply.github.com` : "mastra-code@users.noreply.github.com");
242
- return { name, email };
243
- }
244
- async function configureGitIdentity(sandbox, workdir, identity) {
245
- const { name, email } = resolveGitIdentity(identity);
246
- const setName = await sh(sandbox, `git -C ${shellQuote(workdir)} config user.name ${shellQuote(name)}`);
247
- if (setName.exitCode !== 0) {
248
- throw new MaterializeError(`Failed to set git user.name: ${setName.stderr.trim()}`, "commit-failed");
249
- }
250
- const setEmail = await sh(sandbox, `git -C ${shellQuote(workdir)} config user.email ${shellQuote(email)}`);
251
- if (setEmail.exitCode !== 0) {
252
- throw new MaterializeError(`Failed to set git user.email: ${setEmail.stderr.trim()}`, "commit-failed");
253
- }
254
- }
255
- async function withInstallToken(sandbox, workdir, repoFullName, token, fn) {
256
- if (!/^[\w.-]+\/[\w.-]+$/.test(repoFullName)) {
257
- throw new MaterializeError(`Refusing to push: invalid repo full name '${repoFullName}'.`, "push-failed");
258
- }
259
- const setUrl = await sh(
260
- sandbox,
261
- `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(tokenUrl(repoFullName, token))}`
262
- );
263
- if (setUrl.exitCode !== 0) {
264
- await scrubRemote(sandbox, workdir, repoFullName, false);
265
- throw new MaterializeError(`Failed to set git remote: ${setUrl.stderr.trim()}`, "push-failed");
266
- }
267
- try {
268
- return await fn();
269
- } finally {
270
- await scrubRemote(sandbox, workdir, repoFullName, true);
271
- }
272
- }
273
- async function pushBranch(sandbox, workdir, branch, token, repoFullName) {
274
- if (!isValidGitRef(branch)) {
275
- throw new MaterializeError(`Refusing to push: invalid branch name '${branch}'.`, "push-failed");
276
- }
277
- await withInstallToken(sandbox, workdir, repoFullName, token, async () => {
278
- const push = await sh(sandbox, `git -C ${shellQuote(workdir)} push -u origin ${shellQuote(branch)}`);
279
- if (push.exitCode !== 0) {
280
- throw classifyGitFailure(push, "push-failed");
281
- }
282
- });
283
- }
284
- async function commitAll(sandbox, workdir, message, identity) {
285
- await configureGitIdentity(sandbox, workdir, identity);
286
- const add = await sh(sandbox, `git -C ${shellQuote(workdir)} add -A`);
287
- if (add.exitCode !== 0) {
288
- throw new MaterializeError(`git add failed: ${add.stderr.trim() || add.stdout.trim()}`, "commit-failed");
289
- }
290
- const staged = await sh(sandbox, `git -C ${shellQuote(workdir)} diff --cached --quiet`);
291
- if (staged.exitCode === 0) {
292
- return { committed: false };
293
- }
294
- const commit = await sh(sandbox, `git -C ${shellQuote(workdir)} commit -m ${shellQuote(message)}`);
295
- if (commit.exitCode !== 0) {
296
- throw new MaterializeError(`git commit failed: ${commit.stderr.trim() || commit.stdout.trim()}`, "commit-failed");
297
- }
298
- return { committed: true };
299
- }
300
- var WorktreeError = class extends Error {
301
- constructor(message, code) {
302
- super(message);
303
- this.code = code;
304
- this.name = "WorktreeError";
305
- }
306
- code;
307
- };
308
- function safeBranchDir(branch) {
309
- const sanitized = branch.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/\/+/g, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, 100) || "work";
310
- if (sanitized === branch) return sanitized;
311
- const hash = createHash("sha256").update(branch).digest("hex").slice(0, 8);
312
- return `${sanitized}-${hash}`;
313
- }
314
- function computeWorktreePath(repoWorkdir, branch) {
315
- const parent = repoWorkdir.replace(/\/+$/, "").split("/").slice(0, -1).join("/") || "";
316
- return `${parent}/worktrees/${safeBranchDir(branch)}`;
317
- }
318
-
319
- // src/integrations/github/subscriptions.ts
320
- function changeRequestTargetKey(input) {
321
- return `change-request:${input.installationExternalId}:${input.repositoryExternalId}:${input.changeRequestId}`;
322
- }
323
- function sameSession(row, input) {
324
- return row.orgId === input.orgId && row.sessionId === input.sessionId && row.resourceId === input.resourceId && row.threadId === input.threadId && (row.sessionScope ?? "") === (input.sessionScope ?? "");
325
- }
326
- async function subscribeToPullRequest(input, storage) {
327
- const targetKey = changeRequestTargetKey(input);
328
- const existing = (await storage.subscriptions.listByTarget(targetKey)).find((row) => sameSession(row, input));
329
- if (existing) {
330
- if (existing.status !== "open") await storage.subscriptions.updateStatus(existing.id, "open");
331
- return { ...existing, status: "open" };
332
- }
333
- return storage.subscriptions.create({
334
- orgId: input.orgId,
335
- targetKey,
336
- sessionId: input.sessionId,
337
- resourceId: input.resourceId,
338
- threadId: input.threadId,
339
- sessionScope: input.sessionScope ?? "",
340
- status: "open",
341
- data: {
342
- installationExternalId: input.installationExternalId,
343
- projectRepositoryId: input.projectRepositoryId,
344
- repositoryExternalId: input.repositoryExternalId,
345
- repositorySlug: input.repositorySlug,
346
- changeRequestId: input.changeRequestId,
347
- ownerId: input.ownerId,
348
- source: input.source,
349
- subscribedByUserId: input.subscribedByUserId ?? null
350
- }
351
- });
352
- }
353
- async function unsubscribeFromPullRequest(input, storage) {
354
- const rows = await storage.subscriptions.listByTarget(changeRequestTargetKey(input));
355
- await Promise.all(rows.filter((row) => sameSession(row, input)).map((row) => storage.subscriptions.delete(row.id)));
356
- }
357
- async function listPullRequestSubscriptionsForThread(input, storage) {
358
- const rows = await storage.subscriptions.listByThread(input.resourceId, input.threadId);
359
- return rows.filter(
360
- (row) => row.orgId === input.orgId && row.resourceId === input.resourceId && row.threadId === input.threadId && (row.sessionScope ?? "") === (input.sessionScope ?? "")
361
- );
362
- }
363
- async function listPullRequestSubscriptionsForWebhook(input, options, storage) {
364
- const rows = await storage.subscriptions.listByTarget(changeRequestTargetKey(input));
365
- return options?.includeTerminal ? rows : rows.filter((row) => row.status === "open");
366
- }
367
- function retirePullRequestSubscription(id, status, storage) {
368
- return storage.subscriptions.updateStatus(id, status);
369
- }
370
-
371
- // src/integrations/github/webhook.ts
372
- import { createHmac, timingSafeEqual } from "crypto";
373
- var SUPPORTED_GITHUB_WEBHOOK_EVENTS = /* @__PURE__ */ new Set([
374
- "issues",
375
- "issue_comment",
376
- "pull_request",
377
- "pull_request_review",
378
- "pull_request_review_comment"
379
- ]);
380
- function normalizeHeader(value) {
381
- if (!value) return null;
382
- const trimmed = value.trim();
383
- return trimmed.length > 0 ? trimmed : null;
384
- }
385
- function verifySignature(rawBody, signature, secret) {
386
- if (!signature.startsWith("sha256=")) return false;
387
- const signatureHex = signature.slice("sha256=".length);
388
- if (!/^[a-fA-F0-9]{64}$/.test(signatureHex)) return false;
389
- const expectedHex = createHmac("sha256", secret).update(rawBody).digest("hex");
390
- const received = Buffer.from(signatureHex, "hex");
391
- const expected = Buffer.from(expectedHex, "hex");
392
- return received.length === expected.length && timingSafeEqual(received, expected);
393
- }
394
- async function parseGithubWebhook(c, secret) {
395
- if (!secret) {
396
- return { status: 401, body: { error: "unauthorized", message: "GitHub webhook secret is not configured" } };
397
- }
398
- const event = normalizeHeader(c.req.header("x-github-event"));
399
- const deliveryId = normalizeHeader(c.req.header("x-github-delivery"));
400
- const signature = normalizeHeader(c.req.header("x-hub-signature-256"));
401
- if (!event) return { status: 400, body: { error: "bad_request", message: "Missing x-github-event header" } };
402
- if (!deliveryId) return { status: 400, body: { error: "bad_request", message: "Missing x-github-delivery header" } };
403
- if (!signature)
404
- return { status: 401, body: { error: "unauthorized", message: "Missing x-hub-signature-256 header" } };
405
- const rawBody = await c.req.text();
406
- if (!verifySignature(rawBody, signature, secret)) {
407
- return { status: 401, body: { error: "unauthorized", message: "Invalid GitHub webhook signature" } };
408
- }
409
- let payload;
410
- try {
411
- payload = JSON.parse(rawBody);
412
- } catch {
413
- return { status: 400, body: { error: "bad_request", message: "Malformed JSON payload" } };
414
- }
415
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
416
- return { status: 400, body: { error: "bad_request", message: "Payload must be a JSON object" } };
417
- }
418
- return { event, deliveryId, payload };
419
- }
420
- function getObject(value) {
421
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
422
- }
423
- function getString(value) {
424
- return typeof value === "string" && value.length > 0 ? value : void 0;
425
- }
426
- function getNumber(value) {
427
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
428
- }
429
- function getBoolean(value) {
430
- return typeof value === "boolean" ? value : void 0;
431
- }
432
- function getLabels(value) {
433
- if (!Array.isArray(value)) return [];
434
- return value.map((label) => typeof label === "string" ? label : getString(getObject(label)?.name)).filter((label) => Boolean(label));
435
- }
436
- function getIssueTriageRunInput(parsed) {
437
- if (parsed.event !== "issues" || getString(parsed.payload.action) !== "opened") return null;
438
- const repository = getString(getObject(parsed.payload.repository)?.full_name);
439
- const issue = getObject(parsed.payload.issue);
440
- const sender = getString(getObject(parsed.payload.sender)?.login);
441
- const installationId = getNumber(getObject(parsed.payload.installation)?.id);
442
- const issueNumber = getNumber(issue?.number);
443
- const issueTitle = getString(issue?.title);
444
- const issueUrl = getString(issue?.html_url);
445
- if (!repository || !installationId || !issueNumber || !issueTitle || !issueUrl) return null;
446
- return {
447
- repository,
448
- issueNumber,
449
- issueTitle,
450
- issueUrl,
451
- labels: getLabels(issue?.labels),
452
- sender,
453
- installationId
454
- };
455
- }
456
- function normalizeGithubWebhookMetadata(parsed) {
457
- const { event, deliveryId, payload } = parsed;
458
- const repository = getObject(payload.repository);
459
- const issue = getObject(payload.issue);
460
- const pullRequest = getObject(payload.pull_request);
461
- const sender = getObject(payload.sender);
462
- const installation = getObject(payload.installation);
463
- const issuePullRequest = getObject(issue?.pull_request);
464
- return {
465
- event,
466
- action: getString(payload.action),
467
- deliveryId,
468
- repository: getString(repository?.full_name),
469
- repositoryId: getNumber(repository?.id),
470
- issueNumber: getNumber(issue?.number),
471
- pullRequestNumber: getNumber(pullRequest?.number) ?? (event === "issue_comment" && issuePullRequest ? getNumber(issue?.number) : void 0),
472
- sender: getString(sender?.login),
473
- senderType: getString(sender?.type),
474
- installationId: getNumber(installation?.id)
475
- };
476
- }
477
- function notificationSummary(metadata, label) {
478
- const actor = metadata.sender ? `${metadata.sender} ` : "";
479
- return `${actor}${label} on ${metadata.repository}#${metadata.pullRequestNumber}`;
480
- }
481
- function notificationTargetUrl(event, payload) {
482
- if (event === "issue_comment" || event === "pull_request_review_comment") {
483
- return getString(getObject(payload.comment)?.html_url);
484
- }
485
- if (event === "pull_request_review") {
486
- return getString(getObject(payload.review)?.html_url);
487
- }
488
- return getString(getObject(payload.pull_request)?.html_url);
489
- }
490
- function classifyGithubWebhook(parsed) {
491
- const metadata = normalizeGithubWebhookMetadata(parsed);
492
- const { event, payload } = parsed;
493
- const action = metadata.action;
494
- if (!action || !metadata.repositoryId || !metadata.installationId || !metadata.pullRequestNumber || !metadata.repository) {
495
- return void 0;
496
- }
497
- let priority;
498
- let kind;
499
- let label;
500
- let terminal = false;
501
- if (event === "pull_request_review" && action === "submitted") {
502
- const state = getString(getObject(payload.review)?.state)?.toLowerCase().replaceAll("_", "-");
503
- priority = state === "approved" || state === "changes-requested" ? "urgent" : "high";
504
- kind = state === "approved" ? "review-approved" : state === "changes-requested" ? "review-changes-requested" : "review-submitted";
505
- label = state === "approved" ? "approved the pull request" : state === "changes-requested" ? "requested changes" : "submitted a review";
506
- } else if (event === "pull_request" && action === "closed") {
507
- const merged = getBoolean(getObject(payload.pull_request)?.merged) === true;
508
- priority = "urgent";
509
- kind = merged ? "pull-request-merged" : "pull-request-closed";
510
- label = merged ? "merged the pull request" : "closed the pull request";
511
- terminal = true;
512
- } else if (event === "issue_comment" && action === "created") {
513
- priority = "high";
514
- kind = "issue-comment-created";
515
- label = "commented";
516
- } else if (event === "pull_request_review_comment" && action === "created") {
517
- priority = "high";
518
- kind = "review-comment-created";
519
- label = "left a review comment";
520
- } else if (event === "pull_request" && action === "reopened") {
521
- priority = "high";
522
- kind = "pull-request-reopened";
523
- label = "reopened the pull request";
524
- } else if (event === "pull_request_review" && action === "dismissed") {
525
- priority = "high";
526
- kind = "review-dismissed";
527
- label = "dismissed a review";
528
- } else if (event === "pull_request" && [
529
- "synchronize",
530
- "ready_for_review",
531
- "converted_to_draft",
532
- "assigned",
533
- "unassigned",
534
- "review_requested",
535
- "review_request_removed"
536
- ].includes(action)) {
537
- priority = "medium";
538
- kind = `pull-request-${action.replaceAll("_", "-")}`;
539
- label = action.replaceAll("_", " ");
540
- } else if (event === "pull_request" && ["edited", "labeled", "unlabeled", "milestoned", "demilestoned"].includes(action)) {
541
- priority = "low";
542
- kind = `pull-request-${action.replaceAll("_", "-")}`;
543
- label = action.replaceAll("_", " ");
544
- } else {
545
- return void 0;
546
- }
547
- return {
548
- action,
549
- kind,
550
- priority,
551
- summary: notificationSummary(metadata, label),
552
- terminal,
553
- metadata: {
554
- ...metadata,
555
- pullRequestNumber: metadata.pullRequestNumber,
556
- repositoryId: metadata.repositoryId,
557
- installationId: metadata.installationId
558
- },
559
- payload
560
- };
561
- }
562
- async function resolveSubscriptionSession(controller, subscription) {
563
- const { sessionId, resourceId, threadId } = subscription;
564
- if (!sessionId || !resourceId || !threadId) {
565
- throw new Error(`GitHub subscription ${subscription.id} is missing its session binding.`);
566
- }
567
- const scope = subscription.sessionScope || void 0;
568
- let session = await controller.getSessionByResource(resourceId, scope);
569
- if (!session) {
570
- const tags = {
571
- factoryProjectId: resourceId,
572
- projectRepositoryId: subscription.data.projectRepositoryId,
573
- ...scope ? { worktreePath: scope } : {}
574
- };
575
- session = await controller.createSession({
576
- id: sessionId,
577
- ownerId: subscription.data.ownerId,
578
- resourceId,
579
- scope,
580
- tags
581
- });
582
- }
583
- if (session.thread.getId() !== threadId) {
584
- await session.thread.switch({ threadId, emitEvent: false });
585
- }
586
- if (session.thread.getId() !== threadId) {
587
- throw new Error(`Session ${sessionId} did not bind thread ${threadId}.`);
588
- }
589
- return session;
590
- }
591
- var AUTHORIZED_BOTS = /* @__PURE__ */ new Set(["coderabbitai[bot]", "devin-ai-integration[bot]"]);
592
- var AUTHORIZED_PERMISSIONS = /* @__PURE__ */ new Set(["admin", "maintain", "write"]);
593
- var PERMISSION_CHECK_TIMEOUT_MS = 5e3;
594
- var AUTHOR_GATED_KINDS = /* @__PURE__ */ new Set([
595
- "issue-comment-created",
596
- "review-comment-created",
597
- "review-submitted",
598
- "review-approved",
599
- "review-changes-requested",
600
- "review-dismissed"
601
- ]);
602
- async function isAuthorizedGithubSender(notification, github) {
603
- if (!AUTHOR_GATED_KINDS.has(notification.kind)) return true;
604
- const sender = notification.metadata.sender;
605
- const repository = notification.metadata.repository;
606
- if (!sender || !repository) return false;
607
- const normalizedSender = sender.toLowerCase();
608
- if (notification.metadata.senderType?.toLowerCase() === "bot" || normalizedSender.endsWith("[bot]")) {
609
- return AUTHORIZED_BOTS.has(normalizedSender);
610
- }
611
- if (!github) return false;
612
- const abortController = new AbortController();
613
- let timeout;
614
- try {
615
- const permission = await Promise.race([
616
- github.getRepositoryCollaboratorPermission(
617
- notification.metadata.installationId,
618
- repository,
619
- sender,
620
- abortController.signal
621
- ),
622
- new Promise((resolve) => {
623
- timeout = setTimeout(() => {
624
- abortController.abort();
625
- resolve(void 0);
626
- }, PERMISSION_CHECK_TIMEOUT_MS);
627
- })
628
- ]);
629
- return permission !== void 0 && AUTHORIZED_PERMISSIONS.has(permission);
630
- } catch {
631
- return false;
632
- } finally {
633
- if (timeout) clearTimeout(timeout);
634
- }
635
- }
636
- async function dispatchGithubWebhook(parsed, dependencies) {
637
- const notification = classifyGithubWebhook(parsed);
638
- if (!notification) return { delivered: 0, failed: 0, ignored: true };
639
- const isAuthorizedSender = dependencies.isAuthorizedSender ?? ((n) => isAuthorizedGithubSender(n, dependencies.github));
640
- if (!await isAuthorizedSender(notification)) {
641
- return { delivered: 0, failed: 0, ignored: true };
642
- }
643
- const target = {
644
- installationExternalId: notification.metadata.installationId.toString(),
645
- repositoryExternalId: notification.metadata.repositoryId.toString(),
646
- changeRequestId: notification.metadata.pullRequestNumber.toString()
647
- };
648
- const listSubscriptions = dependencies.listSubscriptions ?? ((subscriptionTarget, options) => {
649
- if (!dependencies.github) throw new Error("GitHub integration is required to load webhook subscriptions.");
650
- return listPullRequestSubscriptionsForWebhook(
651
- subscriptionTarget,
652
- options,
653
- dependencies.github.integrationStorage
654
- );
655
- });
656
- const retireSubscription = dependencies.retireSubscription ?? ((id, status) => {
657
- if (!dependencies.github) throw new Error("GitHub integration is required to retire webhook subscriptions.");
658
- return retirePullRequestSubscription(id, status, dependencies.github.integrationStorage);
659
- });
660
- const subscriptions = await listSubscriptions(target, { includeTerminal: notification.action === "reopened" });
661
- let delivered = 0;
662
- let failed = 0;
663
- for (const subscription of subscriptions) {
664
- try {
665
- const session = await resolveSubscriptionSession(dependencies.controller, subscription);
666
- const result = await session.sendNotificationSignal({
667
- source: "github",
668
- kind: notification.kind,
669
- summary: notification.summary,
670
- priority: notification.priority,
671
- payload: notification.payload,
672
- sourceId: parsed.deliveryId,
673
- dedupeKey: `${parsed.deliveryId}:${subscription.sessionId}:${subscription.threadId}`,
674
- coalesceKey: `github:${subscription.data.repositoryExternalId}:pull-request:${subscription.data.changeRequestId}`,
675
- metadata: {
676
- event: notification.metadata.event,
677
- action: notification.action,
678
- repository: notification.metadata.repository,
679
- issueNumber: notification.metadata.issueNumber,
680
- pullRequestNumber: notification.metadata.pullRequestNumber,
681
- targetUrl: notificationTargetUrl(parsed.event, parsed.payload),
682
- deliveryId: parsed.deliveryId
683
- }
684
- });
685
- await Promise.all([result.persisted, result.accepted].filter(Boolean));
686
- if (notification.terminal) {
687
- await retireSubscription(subscription.id, notification.kind === "pull-request-merged" ? "merged" : "closed");
688
- } else if (notification.action === "reopened") {
689
- await retireSubscription(subscription.id, "open");
690
- }
691
- delivered += 1;
692
- } catch (error) {
693
- failed += 1;
694
- dependencies.onTargetError?.(subscription, error);
695
- }
696
- }
697
- return { delivered, failed, ignored: false };
698
- }
699
- async function handleGithubWebhook(c, options) {
700
- const parsed = await parseGithubWebhook(c, options.github.webhookSecret);
701
- if ("status" in parsed) return parsed;
702
- if (!SUPPORTED_GITHUB_WEBHOOK_EVENTS.has(parsed.event)) {
703
- return { status: 202, body: { ok: true, ignored: true } };
704
- }
705
- const metadata = normalizeGithubWebhookMetadata(parsed);
706
- console.info("[GitHub Webhook]", metadata);
707
- if (options.ingestFactoryEvent) {
708
- await options.ingestFactoryEvent(parsed);
709
- } else {
710
- const issueTriageRun = getIssueTriageRunInput(parsed);
711
- if (issueTriageRun && options.runIssueTriage) {
712
- void options.runIssueTriage(issueTriageRun).catch((error) => {
713
- console.error("[GitHub Webhook] Failed to run issue triage", {
714
- deliveryId: metadata.deliveryId,
715
- repository: metadata.repository,
716
- issueNumber: metadata.issueNumber,
717
- error: error instanceof Error ? error.message : String(error)
718
- });
719
- });
720
- }
721
- }
722
- if (!options.controller) {
723
- return { status: 202, body: { ok: true } };
724
- }
725
- const result = await dispatchGithubWebhook(parsed, options);
726
- if (result.failed > 0) {
727
- console.warn(`[GitHub Webhook] ${result.failed} subscribed target(s) failed for delivery ${parsed.deliveryId}.`);
728
- }
729
- return { status: 202, body: { ok: true, ...result.ignored ? { ignored: true } : {} } };
730
- }
731
-
732
- // src/integrations/github/routes.ts
733
- var sessionOperationLocks = /* @__PURE__ */ new Map();
734
- function withSessionOperationLock(sessionId, fn) {
735
- const previous = sessionOperationLocks.get(sessionId) ?? Promise.resolve();
736
- const next = previous.then(fn, fn);
737
- const tail = next.then(
738
- () => void 0,
739
- () => void 0
740
- );
741
- sessionOperationLocks.set(sessionId, tail);
742
- void tail.then(() => {
743
- if (sessionOperationLocks.get(sessionId) === tail) sessionOperationLocks.delete(sessionId);
744
- });
745
- return next;
746
- }
747
- function loose(c) {
748
- return c;
749
- }
750
- async function resolveFactoryDefaultModelId(projects, factoryProjectId) {
751
- if (!projects || !factoryProjectId) return void 0;
752
- try {
753
- const project = await projects.getById({ id: factoryProjectId });
754
- return project?.defaultModelId ?? void 0;
755
- } catch {
756
- return void 0;
757
- }
758
- }
759
- function pullRequestNumberFromUrl(value, expectedRepo) {
760
- try {
761
- const url = new URL(value);
762
- const match = url.pathname.match(/^\/([^/]+\/[^/]+)\/pull\/(\d+)\/?$/);
763
- if (url.protocol !== "https:" || url.hostname !== "github.com" || match?.[1]?.toLowerCase() !== expectedRepo.toLowerCase()) {
764
- return void 0;
765
- }
766
- const number2 = Number(match[2]);
767
- return Number.isInteger(number2) && number2 > 0 ? number2 : void 0;
768
- } catch {
769
- return void 0;
770
- }
771
- }
772
- function isCanonicalGithubIssueUrl(value, repoFullName, issueNumber) {
773
- try {
774
- const url = new URL(value);
775
- const [owner, repo] = repoFullName.split("/");
776
- return url.protocol === "https:" && url.hostname === "github.com" && url.pathname === `/${owner}/${repo}/issues/${issueNumber}` && url.search === "" && url.hash === "";
777
- } catch {
778
- return false;
779
- }
780
- }
781
- function isValidGitRef2(value) {
782
- return typeof value === "string" && value.length > 0 && value.length <= 255 && /^[A-Za-z0-9_./-]+$/.test(value);
783
- }
784
- async function resolveOrgTenant(c, auth) {
785
- await auth.ensureUser(c);
786
- const tenant = auth.tenant(c);
787
- if (!tenant) return { response: c.json({ error: "unauthorized" }, 401) };
788
- if (!tenant.orgId) {
789
- return {
790
- response: c.json(
791
- {
792
- error: "organization_required",
793
- message: "GitHub projects require a WorkOS organization. Personal accounts cannot connect repositories."
794
- },
795
- 403
796
- )
797
- };
798
- }
799
- return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };
800
- }
801
- function parseListPage(raw) {
802
- if (raw === void 0) return 1;
803
- if (!/^\d{1,5}$/.test(raw)) return null;
804
- const page = Number(raw);
805
- return page >= 1 ? page : null;
806
- }
807
- var VALID_ISSUE_LABEL_FILTERS = /* @__PURE__ */ new Set(["auto-triaged", "needs-approval"]);
808
- function parseIssueLabelFilter(raw) {
809
- if (raw === void 0 || raw === "") return void 0;
810
- if (VALID_ISSUE_LABEL_FILTERS.has(raw)) return raw;
811
- return null;
812
- }
813
- function parseIssueNumberParam(raw) {
814
- if (!raw || !/^\d{1,10}$/.test(raw)) return null;
815
- const issueNumber = Number(raw);
816
- return Number.isSafeInteger(issueNumber) && issueNumber > 0 ? issueNumber : null;
817
- }
818
- function parseStringList(value) {
819
- if (!Array.isArray(value)) return [];
820
- return value.filter((item) => typeof item === "string" && item.length > 0);
821
- }
822
- async function resolveProjectRepository(args) {
823
- const projectRepository = await args.github.sourceControlStorage.projectRepositories.get({
824
- orgId: args.orgId,
825
- id: args.projectRepositoryId
826
- });
827
- if (!projectRepository) return null;
828
- const connection = await args.github.sourceControlStorage.connections.get({
829
- orgId: args.orgId,
830
- id: projectRepository.connectionId
831
- });
832
- if (!connection) return null;
833
- const repository = await args.github.sourceControlStorage.repositories.get({
834
- orgId: args.orgId,
835
- id: projectRepository.repositoryId
836
- });
837
- if (!repository) return null;
838
- const installation = await args.github.sourceControlStorage.installations.get({
839
- orgId: args.orgId,
840
- id: connection.installationId
841
- });
842
- if (!installation) return null;
843
- return {
844
- ...projectRepository,
845
- connection,
846
- installation,
847
- repository,
848
- factoryProjectId: connection.factoryProjectId,
849
- defaultBranch: projectRepository.branch ?? repository.defaultBranch
850
- };
851
- }
852
- function polledIssueEvent(project, issue) {
853
- const repositoryId = Number(project.repository.externalId);
854
- return {
855
- event: "issues",
856
- deliveryId: `poll:${repositoryId}:issue:${issue.number}:${issue.createdAt}`,
857
- payload: {
858
- action: "opened",
859
- installation: { id: Number(project.installation.externalId) },
860
- repository: { id: repositoryId, full_name: project.repository.slug },
861
- sender: { login: issue.author ?? "__unknown__" },
862
- issue: {
863
- number: issue.number,
864
- title: issue.title,
865
- html_url: issue.url,
866
- created_at: issue.createdAt,
867
- labels: issue.labels.map((name) => ({ name }))
868
- }
869
- }
870
- };
871
- }
872
- function polledPullRequestEvent(project, pullRequest) {
873
- const repositoryId = Number(project.repository.externalId);
874
- return {
875
- event: "pull_request",
876
- deliveryId: `poll:${repositoryId}:pull-request:${pullRequest.number}:${pullRequest.createdAt}`,
877
- payload: {
878
- action: "opened",
879
- installation: { id: Number(project.installation.externalId) },
880
- repository: { id: repositoryId, full_name: project.repository.slug },
881
- sender: { login: pullRequest.author ?? "__unknown__" },
882
- pull_request: {
883
- number: pullRequest.number,
884
- title: pullRequest.title,
885
- html_url: pullRequest.url,
886
- created_at: pullRequest.createdAt,
887
- state: "open",
888
- merged: false,
889
- head: { ref: pullRequest.headBranch },
890
- base: { ref: pullRequest.baseBranch }
891
- }
892
- }
893
- };
894
- }
895
- async function ingestPolledEvents(events, ingestFactoryEvent) {
896
- if (!ingestFactoryEvent) return;
897
- const results = await Promise.allSettled(events.map((event) => ingestFactoryEvent(event)));
898
- const rejected = results.find((result) => result.status === "rejected");
899
- if (rejected) throw rejected.reason;
900
- }
901
- function buildGithubRoutes(options) {
902
- const routes = [];
903
- const { auth, fleet, storage, github, stateSigner, emitAudit } = options;
904
- const diagnostics = () => getGithubFeatureDiagnostics({ github, auth, appDbConfigured: storage !== void 0, stateSigner, fleet });
905
- routes.push(
906
- registerApiRoute("/web/github/status", {
907
- method: "GET",
908
- requiresAuth: false,
909
- handler: async (c) => {
910
- if (!isGithubFeatureEnabled({ github, auth }) || !github || !stateSigner) {
911
- return c.json({
912
- enabled: false,
913
- connected: false,
914
- installations: [],
915
- reason: "missing_config",
916
- diagnostics: diagnostics()
917
- });
918
- }
919
- await auth.ensureUser(loose(c));
920
- const tenant = auth.tenant(loose(c));
921
- if (!tenant) return c.json({ error: "unauthorized", reason: "auth_required" }, 401);
922
- if (!tenant.orgId) {
923
- return c.json({
924
- enabled: true,
925
- sandboxEnabled: fleet.enabled,
926
- organizationRequired: true,
927
- connected: false,
928
- installations: [],
929
- reason: "organization_required",
930
- diagnostics: diagnostics()
931
- });
932
- }
933
- const rows = options.github ? await options.github.sourceControlStorage.installations.list({ orgId: tenant.orgId }) : [];
934
- const connected = rows.length > 0;
935
- return c.json({
936
- enabled: true,
937
- sandboxEnabled: fleet.enabled,
938
- connected,
939
- installations: rows.map((r) => ({
940
- installationId: Number(r.externalId),
941
- accountLogin: r.accountName,
942
- accountType: r.accountType
943
- })),
944
- reason: connected ? "ready" : "not_connected",
945
- diagnostics: diagnostics()
946
- });
947
- }
948
- })
949
- );
950
- if (!isGithubFeatureEnabled({ github, auth }) || !github || !stateSigner) {
951
- return routes;
952
- }
953
- const signState = (orgId, userId) => stateSigner.sign(orgId, userId);
954
- const verifyState = (state) => stateSigner.verify(state);
955
- const { runIssueTriage } = options;
956
- const runBoardIssueTriage = runIssueTriage ? async (input) => {
957
- if (!input.resourceId || !input.projectPath) {
958
- throw new Error("GitHub issue triage requires an explicit Factory project repository");
959
- }
960
- await github.addIssueLabels(input.installationId, input.repository, input.issueNumber, ["auto-triaged"]);
961
- return runIssueTriage({
962
- ...input,
963
- defaultModelId: input.defaultModelId ?? await resolveFactoryDefaultModelId(options.projects, input.resourceId),
964
- labels: input.labels.includes("auto-triaged") ? input.labels : [...input.labels, "auto-triaged"]
965
- });
966
- } : void 0;
967
- routes.push(
968
- registerApiRoute("/web/github/subscriptions", {
969
- method: "GET",
970
- handler: async (c) => {
971
- await auth.ensureUser(loose(c));
972
- const tenant = auth.tenant(loose(c));
973
- if (!tenant?.orgId) return c.json({ error: "unauthorized" }, 401);
974
- const resourceId = c.req.query("resourceId");
975
- const threadId = c.req.query("threadId");
976
- const sessionScope = c.req.query("scope");
977
- if (!resourceId || !threadId) return c.json({ error: "resourceId and threadId are required" }, 400);
978
- const subscriptions = await listPullRequestSubscriptionsForThread(
979
- {
980
- orgId: tenant.orgId,
981
- resourceId,
982
- threadId,
983
- sessionScope
984
- },
985
- github.integrationStorage
986
- );
987
- return c.json({
988
- subscriptions: subscriptions.map((subscription) => ({
989
- id: subscription.id,
990
- repoFullName: subscription.data.repositorySlug,
991
- pullRequestNumber: Number(subscription.data.changeRequestId),
992
- status: subscription.status,
993
- url: `https://github.com/${subscription.data.repositorySlug}/pull/${subscription.data.changeRequestId}`
994
- }))
995
- });
996
- }
997
- }),
998
- registerApiRoute("/web/github/webhook", {
999
- method: "POST",
1000
- requiresAuth: false,
1001
- handler: async (c) => {
1002
- const result = await handleGithubWebhook(loose(c), {
1003
- github,
1004
- runIssueTriage: runBoardIssueTriage,
1005
- ingestFactoryEvent: options.ingestFactoryEvent,
1006
- ...options.controller ? {
1007
- controller: options.controller,
1008
- onTargetError: (subscription, error) => {
1009
- console.warn(
1010
- `[GitHub Webhook] Delivery failed for subscription ${subscription.id} (${subscription.resourceId}/${subscription.threadId}).`,
1011
- error
1012
- );
1013
- }
1014
- } : {}
1015
- });
1016
- return c.json(result.body, result.status);
1017
- }
1018
- })
1019
- );
1020
- const redirectUri = options.redirectUri ?? `${(options.baseUrl ?? "").replace(/\/$/, "")}/auth/github/callback`;
1021
- routes.push(
1022
- registerApiRoute("/auth/github/connect", {
1023
- method: "GET",
1024
- requiresAuth: false,
1025
- handler: async (c) => {
1026
- const resolved = await resolveOrgTenant(loose(c), auth);
1027
- if ("response" in resolved) return resolved.response;
1028
- const state = signState(resolved.tenant.orgId, resolved.tenant.userId);
1029
- if (c.req.query("manage")) return c.redirect(github.buildInstallUrl(state));
1030
- return c.redirect(github.buildOAuthIdentifyUrl(state, redirectUri));
1031
- }
1032
- })
1033
- );
1034
- routes.push(
1035
- registerApiRoute("/auth/github/callback", {
1036
- method: "GET",
1037
- requiresAuth: false,
1038
- handler: async (c) => {
1039
- const resolved = await resolveOrgTenant(loose(c), auth);
1040
- if ("response" in resolved) return resolved.response;
1041
- const { orgId, userId } = resolved.tenant;
1042
- const state = c.req.query("state");
1043
- if (!state) {
1044
- return c.redirect(github.buildOAuthIdentifyUrl(signState(orgId, userId), redirectUri));
1045
- }
1046
- const stateTenant = verifyState(state);
1047
- if (!stateTenant || stateTenant.userId !== userId || stateTenant.orgId !== orgId) {
1048
- console.warn(
1049
- "[GitHub] Install callback rejected: state/tenant mismatch.",
1050
- JSON.stringify({
1051
- stateValid: Boolean(stateTenant),
1052
- stateOrgId: stateTenant?.orgId,
1053
- stateUserId: stateTenant?.userId,
1054
- sessionOrgId: orgId,
1055
- sessionUserId: userId
1056
- })
1057
- );
1058
- return c.redirect("/?github=error");
1059
- }
1060
- const code = c.req.query("code");
1061
- if (!code) {
1062
- return c.redirect(github.buildOAuthIdentifyUrl(signState(orgId, userId), redirectUri));
1063
- }
1064
- try {
1065
- const userToken = await github.exchangeOAuthCode(code, redirectUri);
1066
- const installations = await github.listUserInstallations(userToken);
1067
- if (installations.length === 0) {
1068
- return c.redirect(github.buildInstallUrl(signState(orgId, userId)));
1069
- }
1070
- for (const inst of installations) {
1071
- await github.sourceControlStorage.installations.upsert({
1072
- orgId,
1073
- connectedByUserId: userId,
1074
- externalId: inst.installationId.toString(),
1075
- accountName: inst.accountLogin,
1076
- accountType: inst.accountType
1077
- });
1078
- }
1079
- } catch (error) {
1080
- console.warn(
1081
- `[GitHub] Install callback failed to persist installations for org ${orgId} / user ${userId}.`,
1082
- error
1083
- );
1084
- return c.redirect("/?github=error");
1085
- }
1086
- return c.redirect("/?github=connected");
1087
- }
1088
- })
1089
- );
1090
- routes.push(
1091
- registerApiRoute("/web/github/repos", {
1092
- method: "GET",
1093
- requiresAuth: false,
1094
- handler: async (c) => {
1095
- const resolved = await resolveOrgTenant(loose(c), auth);
1096
- if ("response" in resolved) return resolved.response;
1097
- const orgId = resolved.tenant.orgId;
1098
- const installs = await github.sourceControlStorage.installations.list({ orgId });
1099
- const query = (c.req.query("q") ?? "").toLowerCase();
1100
- const listed = await Promise.all(
1101
- installs.map(async (inst) => {
1102
- try {
1103
- return { inst, list: await github.listInstallationRepos(Number(inst.externalId)) };
1104
- } catch (err) {
1105
- if (err.status !== 404) throw err;
1106
- console.error(`[Mastra Factory] pruning stale GitHub installation ${inst.externalId} (404 from GitHub)`);
1107
- await github.sourceControlStorage.installations.delete({ orgId, id: inst.id });
1108
- return { inst, list: [] };
1109
- }
1110
- })
1111
- );
1112
- const matches = [];
1113
- const seenRepositoryIds = /* @__PURE__ */ new Set();
1114
- for (const { inst, list } of listed) {
1115
- for (const repo of list) {
1116
- if (query && !repo.fullName.toLowerCase().includes(query)) continue;
1117
- if (seenRepositoryIds.has(repo.id)) continue;
1118
- seenRepositoryIds.add(repo.id);
1119
- matches.push({ inst, repo });
1120
- }
1121
- }
1122
- const repos = new Array(matches.length);
1123
- const upsertConcurrency = 10;
1124
- for (let start = 0; start < matches.length; start += upsertConcurrency) {
1125
- await Promise.all(
1126
- matches.slice(start, start + upsertConcurrency).map(async ({ inst, repo }, offset) => {
1127
- const repository = await github.sourceControlStorage.repositories.upsert({
1128
- orgId,
1129
- input: {
1130
- installationId: inst.id,
1131
- externalId: repo.id.toString(),
1132
- slug: repo.fullName,
1133
- defaultBranch: isValidGitRef2(repo.defaultBranch) ? repo.defaultBranch : "main",
1134
- providerMetadata: { private: repo.private, owner: repo.owner }
1135
- }
1136
- });
1137
- repos[start + offset] = {
1138
- ...repo,
1139
- installationStorageId: inst.id,
1140
- repositoryStorageId: repository.id,
1141
- sandboxProvider: fleet.provider,
1142
- sandboxWorkdir: fleet.computeWorkdir(repo.fullName)
1143
- };
1144
- })
1145
- );
1146
- }
1147
- return c.json({ repos });
1148
- }
1149
- })
1150
- );
1151
- routes.push(
1152
- registerApiRoute("/web/github/projects/:id/ensure", {
1153
- method: "POST",
1154
- requiresAuth: false,
1155
- handler: async (c) => {
1156
- const resolved = await resolveOrgTenant(loose(c), auth);
1157
- if ("response" in resolved) return resolved.response;
1158
- const { orgId, userId } = resolved.tenant;
1159
- if (!fleet.enabled) {
1160
- return c.json({ error: "sandbox_not_configured", message: "No sandbox provider is configured." }, 503);
1161
- }
1162
- const projectRepositoryId = c.req.param("id");
1163
- if (!projectRepositoryId) return c.json({ error: "Project repository not found" }, 404);
1164
- const project = await resolveProjectRepository({ github, orgId, projectRepositoryId });
1165
- if (!project) {
1166
- return c.json({ error: "Project repository not found" }, 404);
1167
- }
1168
- const wantsStream = (c.req.header("accept") ?? "").includes("text/event-stream");
1169
- if (wantsStream) {
1170
- return streamSSE(loose(c), async (stream) => {
1171
- try {
1172
- const result = await prepareProject({
1173
- github,
1174
- fleet,
1175
- project,
1176
- userId,
1177
- onProgress: (ev) => void stream.writeSSE({ event: "progress", data: JSON.stringify(ev) })
1178
- });
1179
- await stream.writeSSE({ event: "done", data: JSON.stringify(result) });
1180
- } catch (err) {
1181
- await stream.writeSSE({ event: "error", data: JSON.stringify(ensureErrorPayload(err).body) });
1182
- }
1183
- });
1184
- }
1185
- try {
1186
- const result = await prepareProject({ github, fleet, project, userId });
1187
- return c.json(result);
1188
- } catch (err) {
1189
- const { status, body } = ensureErrorPayload(err);
1190
- return c.json(body, status);
1191
- }
1192
- }
1193
- })
1194
- );
1195
- routes.push(
1196
- registerApiRoute("/web/github/projects/:id/issues", {
1197
- method: "GET",
1198
- requiresAuth: false,
1199
- handler: async (c) => {
1200
- const loaded = await loadOrgProject({ github, auth, c: loose(c) });
1201
- if ("response" in loaded) return loaded.response;
1202
- const page = parseListPage(c.req.query("page"));
1203
- if (page === null) return c.json({ error: "invalid_page" }, 400);
1204
- const label = parseIssueLabelFilter(c.req.query("label"));
1205
- if (label === null) return c.json({ error: "invalid_label" }, 400);
1206
- try {
1207
- const { issues, nextCursor } = await github.intake.listIssues({
1208
- connection: {
1209
- type: "app-installation",
1210
- installationId: Number(loaded.project.installation.externalId)
1211
- },
1212
- sourceIds: [loaded.project.repository.slug],
1213
- labels: label ? [label] : void 0,
1214
- cursor: String(page)
1215
- });
1216
- const responseIssues = issues.map((issue) => ({
1217
- number: Number(issue.id),
1218
- title: issue.title,
1219
- url: issue.url,
1220
- author: issue.author,
1221
- labels: issue.labels,
1222
- comments: issue.commentCount ?? 0,
1223
- createdAt: issue.createdAt,
1224
- updatedAt: issue.updatedAt
1225
- }));
1226
- await ingestPolledEvents(
1227
- responseIssues.map((issue) => polledIssueEvent(loaded.project, issue)),
1228
- options.ingestFactoryEvent
1229
- );
1230
- return c.json({
1231
- issues: responseIssues,
1232
- nextPage: nextCursor === null ? null : Number(nextCursor)
1233
- });
1234
- } catch (err) {
1235
- return c.json(
1236
- { error: "github_fetch_failed", message: err instanceof Error ? err.message : String(err) },
1237
- 502
1238
- );
1239
- }
1240
- }
1241
- })
1242
- );
1243
- routes.push(
1244
- registerApiRoute("/web/github/projects/:id/issues/:number/triage", {
1245
- method: "POST",
1246
- requiresAuth: false,
1247
- handler: async (c) => {
1248
- const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
1249
- if ("response" in owned) return owned.response;
1250
- const { project, sandboxRow } = owned;
1251
- const issueNumber = parseIssueNumberParam(c.req.param("number"));
1252
- if (issueNumber === null) return c.json({ error: "invalid_issue_number" }, 400);
1253
- let body;
1254
- try {
1255
- body = await c.req.json();
1256
- } catch {
1257
- return c.json({ error: "Invalid JSON body" }, 400);
1258
- }
1259
- if (typeof body.title !== "string" || body.title.trim().length === 0 || body.title.length > 5e3) {
1260
- return c.json({ error: "invalid_title" }, 400);
1261
- }
1262
- if (typeof body.url !== "string" || body.url.trim().length === 0 || body.url.length > 2048 || !isCanonicalGithubIssueUrl(body.url, project.repository.slug, issueNumber)) {
1263
- return c.json({ error: "invalid_url" }, 400);
1264
- }
1265
- if (!runIssueTriage) return c.json({ error: "triage_unavailable" }, 503);
1266
- const branch = `factory/issue-${issueNumber}`;
1267
- const projectPath = computeWorktreePath(sandboxRow.sandboxWorkdir, branch);
1268
- await github.addIssueLabels(Number(project.installation.externalId), project.repository.slug, issueNumber, [
1269
- "auto-triaged"
1270
- ]);
1271
- const result = await runIssueTriage({
1272
- repository: project.repository.slug,
1273
- issueNumber,
1274
- issueTitle: body.title,
1275
- issueUrl: body.url,
1276
- labels: parseStringList(body.labels),
1277
- installationId: Number(project.installation.externalId),
1278
- resourceId: project.factoryProjectId,
1279
- projectPath,
1280
- branch,
1281
- defaultModelId: await resolveFactoryDefaultModelId(options.projects, project.factoryProjectId)
1282
- });
1283
- await emitAudit?.({
1284
- context: loose(c),
1285
- input: {
1286
- action: "factory.triage.started",
1287
- factoryProjectId: project.factoryProjectId,
1288
- projectRepositoryId: project.id,
1289
- targets: [{ type: "issue", id: String(issueNumber), name: body.title }],
1290
- metadata: { issueNumber, branch, threadId: result.threadId }
1291
- }
1292
- });
1293
- return c.json(
1294
- {
1295
- ok: true,
1296
- threadId: result.threadId,
1297
- projectPath: result.projectPath ?? projectPath,
1298
- branch: result.branch ?? branch
1299
- },
1300
- 202
1301
- );
1302
- }
1303
- })
1304
- );
1305
- routes.push(
1306
- registerApiRoute("/web/github/projects/:id/prs", {
1307
- method: "GET",
1308
- requiresAuth: false,
1309
- handler: async (c) => {
1310
- const loaded = await loadOrgProject({ github, auth, c: loose(c) });
1311
- if ("response" in loaded) return loaded.response;
1312
- const page = parseListPage(c.req.query("page"));
1313
- if (page === null) return c.json({ error: "invalid_page" }, 400);
1314
- try {
1315
- const { pullRequests, nextCursor } = await github.versionControl.listPullRequests({
1316
- connection: {
1317
- type: "app-installation",
1318
- installationId: Number(loaded.project.installation.externalId)
1319
- },
1320
- sourceId: loaded.project.repository.slug,
1321
- includeDrafts: false,
1322
- cursor: String(page)
1323
- });
1324
- const responsePullRequests = pullRequests.map((pr) => ({
1325
- number: Number(pr.id),
1326
- title: pr.title,
1327
- url: pr.url,
1328
- author: pr.author,
1329
- baseBranch: pr.baseBranch,
1330
- headBranch: pr.headBranch,
1331
- createdAt: pr.createdAt,
1332
- updatedAt: pr.updatedAt
1333
- }));
1334
- await ingestPolledEvents(
1335
- responsePullRequests.map((pullRequest) => polledPullRequestEvent(loaded.project, pullRequest)),
1336
- options.ingestFactoryEvent
1337
- );
1338
- return c.json({
1339
- pullRequests: responsePullRequests,
1340
- nextPage: nextCursor === null ? null : Number(nextCursor)
1341
- });
1342
- } catch (err) {
1343
- return c.json(
1344
- { error: "github_fetch_failed", message: err instanceof Error ? err.message : String(err) },
1345
- 502
1346
- );
1347
- }
1348
- }
1349
- })
1350
- );
1351
- routes.push(
1352
- registerApiRoute("/web/github/projects/:id/settings", {
1353
- method: "GET",
1354
- requiresAuth: false,
1355
- handler: async (c) => {
1356
- const loaded = await loadOrgProject({ github, auth, c: loose(c) });
1357
- if ("response" in loaded) return loaded.response;
1358
- return c.json({ setupCommand: loaded.project.setupCommand });
1359
- }
1360
- })
1361
- );
1362
- routes.push(
1363
- registerApiRoute("/web/github/projects/:id/settings", {
1364
- method: "POST",
1365
- requiresAuth: false,
1366
- handler: async (c) => {
1367
- const loaded = await loadOrgProject({ github, auth, c: loose(c) });
1368
- if ("response" in loaded) return loaded.response;
1369
- let body;
1370
- try {
1371
- body = await c.req.json();
1372
- } catch {
1373
- return c.json({ error: "Invalid JSON body" }, 400);
1374
- }
1375
- if (body.setupCommand !== null && typeof body.setupCommand !== "string") {
1376
- return c.json({ error: "Invalid setupCommand" }, 400);
1377
- }
1378
- if (typeof body.setupCommand === "string" && body.setupCommand.length > 2e3) {
1379
- return c.json({ error: "setupCommand too long (max 2000 characters)" }, 400);
1380
- }
1381
- if (typeof body.setupCommand === "string" && /[\0-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(body.setupCommand)) {
1382
- return c.json({ error: "setupCommand contains control characters" }, 400);
1383
- }
1384
- const setupCommand = typeof body.setupCommand === "string" && body.setupCommand.trim().length > 0 ? body.setupCommand.trim() : null;
1385
- await github.sourceControlStorage.projectRepositories.update({
1386
- orgId: loaded.project.installation.orgId,
1387
- id: loaded.project.id,
1388
- input: { setupCommand }
1389
- });
1390
- return c.json({ setupCommand });
1391
- }
1392
- })
1393
- );
1394
- const parsePatKind = (value) => {
1395
- if (value === void 0 || value === null || value === "default") return "default";
1396
- if (value === "reviewer") return "reviewer";
1397
- return null;
1398
- };
1399
- routes.push(
1400
- registerApiRoute("/web/github/pat", {
1401
- method: "GET",
1402
- requiresAuth: false,
1403
- handler: async (c) => {
1404
- const resolved = await resolveOrgTenant(loose(c), auth);
1405
- if ("response" in resolved) return resolved.response;
1406
- return c.json(await getGithubPatStatus(() => github.integrationStorage, resolved.tenant.orgId));
1407
- }
1408
- }),
1409
- registerApiRoute("/web/github/pat", {
1410
- method: "POST",
1411
- requiresAuth: false,
1412
- handler: async (c) => {
1413
- const resolved = await resolveOrgTenant(loose(c), auth);
1414
- if ("response" in resolved) return resolved.response;
1415
- let body;
1416
- try {
1417
- body = await c.req.json();
1418
- } catch {
1419
- return c.json({ error: "Invalid JSON body" }, 400);
1420
- }
1421
- const kind = parsePatKind(body.kind);
1422
- if (!kind) return c.json({ error: "kind must be 'default' or 'reviewer'" }, 400);
1423
- const token = typeof body.token === "string" ? body.token.trim() : "";
1424
- if (!token) return c.json({ error: "A token is required" }, 400);
1425
- if (token.length > 500) return c.json({ error: "Token too long (max 500 characters)" }, 400);
1426
- if (/\s/.test(token)) return c.json({ error: "Token must not contain whitespace" }, 400);
1427
- await setGithubPat(github.integrationStorage, resolved.tenant.orgId, token, kind);
1428
- return c.json(await getGithubPatStatus(() => github.integrationStorage, resolved.tenant.orgId));
1429
- }
1430
- }),
1431
- registerApiRoute("/web/github/pat", {
1432
- method: "DELETE",
1433
- requiresAuth: false,
1434
- handler: async (c) => {
1435
- const resolved = await resolveOrgTenant(loose(c), auth);
1436
- if ("response" in resolved) return resolved.response;
1437
- const kind = parsePatKind(c.req.query("kind"));
1438
- if (!kind) return c.json({ error: "kind must be 'default' or 'reviewer'" }, 400);
1439
- await clearGithubPat(github.integrationStorage, resolved.tenant.orgId, kind);
1440
- return c.json(await getGithubPatStatus(() => github.integrationStorage, resolved.tenant.orgId));
1441
- }
1442
- })
1443
- );
1444
- routes.push(...buildProjectGitRoutes({ github, auth, fleet, emitAudit }));
1445
- return routes;
1446
- }
1447
- async function loadOrgProject(options) {
1448
- const { github, auth, c } = options;
1449
- const resolved = await resolveOrgTenant(c, auth);
1450
- if ("response" in resolved) return { response: resolved.response };
1451
- const { orgId, userId } = resolved.tenant;
1452
- const projectRepositoryId = c.req.param("id");
1453
- if (!projectRepositoryId) {
1454
- return { response: c.json({ error: "Project repository not found" }, 404) };
1455
- }
1456
- const project = await resolveProjectRepository({ github, orgId, projectRepositoryId });
1457
- if (!project) {
1458
- return { response: c.json({ error: "Project repository not found" }, 404) };
1459
- }
1460
- return { project, userId };
1461
- }
1462
- function identityFromUser(user) {
1463
- const u = user;
1464
- return { name: u?.name ?? null, email: u?.email ?? null };
1465
- }
1466
- async function resolveProjectSandbox(options) {
1467
- const { fleet, sandboxRow } = options;
1468
- if (!sandboxRow.sandboxId) {
1469
- throw new MaterializeError("Project sandbox is not provisioned. Open the project first.", "clone-failed");
1470
- }
1471
- return fleet.reattachSandbox(sandboxRow.sandboxId);
1472
- }
1473
- async function loadOrCreateSandboxRow(github, project, userId) {
1474
- return github.sourceControlStorage.sandboxes.getOrCreate({ projectRepository: project, userId });
1475
- }
1476
- async function prepareProject(options) {
1477
- const { github, fleet, userId, onProgress } = options;
1478
- let project = options.project;
1479
- if (project.sandboxProvider !== fleet.provider) {
1480
- const sandboxWorkdir = fleet.computeWorkdir(project.repository.slug);
1481
- await github.sourceControlStorage.projectRepositories.update({
1482
- orgId: project.installation.orgId,
1483
- id: project.id,
1484
- input: { sandboxProvider: fleet.provider, sandboxWorkdir }
1485
- });
1486
- project = { ...project, sandboxProvider: fleet.provider, sandboxWorkdir };
1487
- }
1488
- let sandboxRow = await loadOrCreateSandboxRow(github, project, userId);
1489
- if (sandboxRow.sandboxWorkdir !== project.sandboxWorkdir) {
1490
- await github.sourceControlStorage.sandboxes.setWorkdir({
1491
- id: sandboxRow.id,
1492
- sandboxWorkdir: project.sandboxWorkdir
1493
- });
1494
- sandboxRow = { ...sandboxRow, sandboxWorkdir: project.sandboxWorkdir, materializedAt: null };
1495
- }
1496
- const access = await github.versionControl.getRepositoryAccess({
1497
- orgId: project.installation.orgId,
1498
- repositoryId: project.repository.id
1499
- });
1500
- if (!access.authorization) {
1501
- throw new MaterializeError("Repository access did not include a bearer token.", "clone-failed");
1502
- }
1503
- const ghCliToken = await getGithubPat(() => github.integrationStorage, project.installation.orgId) ?? access.authorization.token;
1504
- const sandbox = await ensureProjectSandbox({
1505
- fleet,
1506
- row: sandboxRow,
1507
- storage: github.sourceControlStorage.sandboxes,
1508
- token: ghCliToken,
1509
- onProgress
1510
- });
1511
- const fresh = await github.sourceControlStorage.sandboxes.getById({ id: sandboxRow.id });
1512
- const finalRow = fresh ?? sandboxRow;
1513
- await materializeRepo({
1514
- row: finalRow,
1515
- repoInfo: { repoFullName: project.repository.slug, defaultBranch: project.defaultBranch },
1516
- sandbox,
1517
- token: access.authorization.token,
1518
- storage: github.sourceControlStorage.sandboxes,
1519
- onProgress
1520
- });
1521
- const result = {
1522
- resourceId: project.factoryProjectId,
1523
- factoryProjectId: project.factoryProjectId,
1524
- projectRepositoryId: project.id,
1525
- sandboxId: finalRow.sandboxId,
1526
- sandboxWorkdir: finalRow.sandboxWorkdir
1527
- };
1528
- const done = { phase: "done", message: "Workspace ready." };
1529
- onProgress?.(done);
1530
- return result;
1531
- }
1532
- function ensureErrorPayload(err) {
1533
- if (err instanceof SandboxBudgetError) {
1534
- return { status: 429, body: { error: err.code, message: err.message } };
1535
- }
1536
- if (err instanceof MaterializeError) {
1537
- return { status: 502, body: { error: err.code, message: err.message } };
1538
- }
1539
- return {
1540
- status: 500,
1541
- body: { error: "materialize_failed", message: err instanceof Error ? err.message : String(err) }
1542
- };
1543
- }
1544
- function gitErrorResponse(c, err) {
1545
- if (err instanceof WorktreeError) {
1546
- return c.json({ error: err.code, message: err.message }, err.code === "invalid-branch" ? 400 : 502);
1547
- }
1548
- if (err instanceof MaterializeError) {
1549
- return c.json({ error: err.code, message: err.message }, 502);
1550
- }
1551
- return c.json({ error: "git_failed", message: err instanceof Error ? err.message : String(err) }, 500);
1552
- }
1553
- async function loadOwnedProject(options) {
1554
- const { github, auth, fleet, c } = options;
1555
- const resolved = await resolveOrgTenant(c, auth);
1556
- if ("response" in resolved) return { response: resolved.response };
1557
- const { orgId, userId } = resolved.tenant;
1558
- if (!fleet.enabled) {
1559
- return {
1560
- response: c.json({ error: "sandbox_not_configured", message: "No sandbox provider is configured." }, 503)
1561
- };
1562
- }
1563
- const projectRepositoryId = c.req.param("id");
1564
- if (!projectRepositoryId) {
1565
- return { response: c.json({ error: "Project repository not found" }, 404) };
1566
- }
1567
- const project = await resolveProjectRepository({ github, orgId, projectRepositoryId });
1568
- if (!project) {
1569
- return { response: c.json({ error: "Project repository not found" }, 404) };
1570
- }
1571
- const sandboxRow = await loadOrCreateSandboxRow(github, project, userId);
1572
- return { orgId, userId, project, sandboxRow };
1573
- }
1574
- function buildProjectGitRoutes({
1575
- github,
1576
- auth,
1577
- fleet,
1578
- emitAudit
1579
- }) {
1580
- return [
1581
- // ── Create / list Factory sessions ──────────────────────────────────────
1582
- registerApiRoute("/web/github/projects/:id/sessions", {
1583
- method: "GET",
1584
- requiresAuth: false,
1585
- handler: async (c) => {
1586
- const resolved = await resolveOrgTenant(loose(c), auth);
1587
- if ("response" in resolved) return resolved.response;
1588
- const { orgId, userId } = resolved.tenant;
1589
- const projectRepositoryId = c.req.param("id");
1590
- const project = projectRepositoryId ? await resolveProjectRepository({ github, orgId, projectRepositoryId }) : null;
1591
- if (!project) return c.json({ error: "Project repository not found" }, 404);
1592
- const sessions = await github.sourceControlStorage.sessions.list({ projectRepositoryId: project.id, userId });
1593
- return c.json({ sessions });
1594
- }
1595
- }),
1596
- registerApiRoute("/web/github/projects/:id/sessions", {
1597
- method: "POST",
1598
- requiresAuth: false,
1599
- handler: async (c) => {
1600
- const resolved = await resolveOrgTenant(loose(c), auth);
1601
- if ("response" in resolved) return resolved.response;
1602
- const { orgId, userId } = resolved.tenant;
1603
- const projectRepositoryId = c.req.param("id");
1604
- const project = projectRepositoryId ? await resolveProjectRepository({ github, orgId, projectRepositoryId }) : null;
1605
- if (!project) return c.json({ error: "Project repository not found" }, 404);
1606
- let body;
1607
- try {
1608
- body = await c.req.json();
1609
- } catch {
1610
- return c.json({ error: "Invalid JSON body" }, 400);
1611
- }
1612
- if (!isValidGitRef(body.branch)) return c.json({ error: "Invalid branch" }, 400);
1613
- const baseBranch = body.baseBranch === void 0 ? project.defaultBranch : body.baseBranch;
1614
- if (!isValidGitRef(baseBranch)) return c.json({ error: "Invalid baseBranch" }, 400);
1615
- const session = await github.sourceControlStorage.sessions.create({
1616
- sessionId: randomUUID(),
1617
- projectRepositoryId: project.id,
1618
- orgId,
1619
- userId,
1620
- branch: body.branch,
1621
- baseBranch
1622
- });
1623
- return c.json({ session });
1624
- }
1625
- }),
1626
- registerApiRoute("/web/user-sessions/:sessionId", {
1627
- method: "GET",
1628
- requiresAuth: false,
1629
- handler: async (c) => {
1630
- const resolved = await resolveOrgTenant(loose(c), auth);
1631
- if ("response" in resolved) return resolved.response;
1632
- const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
1633
- if (!session || session.orgId !== resolved.tenant.orgId || session.userId !== resolved.tenant.userId) {
1634
- return c.json({ error: "Session not found" }, 404);
1635
- }
1636
- return c.json({ session });
1637
- }
1638
- }),
1639
- registerApiRoute("/web/user-sessions/:sessionId", {
1640
- method: "DELETE",
1641
- requiresAuth: false,
1642
- handler: async (c) => {
1643
- const resolved = await resolveOrgTenant(loose(c), auth);
1644
- if ("response" in resolved) return resolved.response;
1645
- const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
1646
- if (!session || session.orgId !== resolved.tenant.orgId || session.userId !== resolved.tenant.userId) {
1647
- return c.json({ error: "Session not found" }, 404);
1648
- }
1649
- let sandbox;
1650
- if (session.sandboxId) {
1651
- try {
1652
- sandbox = await fleet.reattachSandbox(session.sandboxId);
1653
- } catch {
1654
- }
1655
- await fleet.teardownSandbox(
1656
- {
1657
- sandboxId: session.sandboxId,
1658
- setSandboxId: async () => {
1659
- },
1660
- clear: async () => {
1661
- await github.sourceControlStorage.sessions.setSandbox({
1662
- id: session.id,
1663
- sandboxId: null,
1664
- sandboxWorkdir: session.sandboxWorkdir ?? ""
1665
- });
1666
- }
1667
- },
1668
- sandbox
1669
- );
1670
- }
1671
- await github.sourceControlStorage.sessions.delete(session.id);
1672
- return c.json({ removed: true });
1673
- }
1674
- }),
1675
- // ── Stage all + commit inside a Factory session workspace ──────────────
1676
- registerApiRoute("/web/github/projects/:id/commit", {
1677
- method: "POST",
1678
- requiresAuth: false,
1679
- handler: async (c) => {
1680
- const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
1681
- if ("response" in owned) return owned.response;
1682
- const { userId, project } = owned;
1683
- let body;
1684
- try {
1685
- body = await c.req.json();
1686
- } catch {
1687
- return c.json({ error: "Invalid JSON body" }, 400);
1688
- }
1689
- if (typeof body.message !== "string" || body.message.trim().length === 0 || body.message.length > 5e3) {
1690
- return c.json({ error: "Invalid message" }, 400);
1691
- }
1692
- const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
1693
- if (!sessionWorkspace) {
1694
- return c.json({ error: "Invalid sessionId" }, 400);
1695
- }
1696
- const { workdir, sandboxBinding } = sessionWorkspace;
1697
- try {
1698
- return await withSessionOperationLock(sessionWorkspace.session.sessionId, async () => {
1699
- const sandbox = await resolveProjectSandbox({ fleet, sandboxRow: sandboxBinding });
1700
- const result = await commitAll(
1701
- sandbox,
1702
- workdir,
1703
- body.message,
1704
- identityFromUser(await auth.ensureUser(loose(c)))
1705
- );
1706
- if (result.committed) {
1707
- await emitAudit?.({
1708
- context: loose(c),
1709
- input: {
1710
- action: "factory.git.commit",
1711
- factoryProjectId: project.factoryProjectId,
1712
- projectRepositoryId: project.id,
1713
- targets: [{ type: "session", id: sessionWorkspace.session.sessionId }],
1714
- metadata: { sessionId: sessionWorkspace.session.sessionId }
1715
- }
1716
- });
1717
- }
1718
- return c.json({ committed: result.committed });
1719
- });
1720
- } catch (err) {
1721
- return gitErrorResponse(loose(c), err);
1722
- }
1723
- }
1724
- }),
1725
- // ── Push a branch back to GitHub ────────────────────────────────────────
1726
- registerApiRoute("/web/github/projects/:id/push", {
1727
- method: "POST",
1728
- requiresAuth: false,
1729
- handler: async (c) => {
1730
- const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
1731
- if ("response" in owned) return owned.response;
1732
- const { orgId, userId, project } = owned;
1733
- let body;
1734
- try {
1735
- body = await c.req.json();
1736
- } catch {
1737
- return c.json({ error: "Invalid JSON body" }, 400);
1738
- }
1739
- if (!isValidGitRef(body.branch)) {
1740
- return c.json({ error: "Invalid branch" }, 400);
1741
- }
1742
- const branch = body.branch;
1743
- const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
1744
- if (!sessionWorkspace) {
1745
- return c.json({ error: "Invalid sessionId" }, 400);
1746
- }
1747
- const { workdir, sandboxBinding } = sessionWorkspace;
1748
- try {
1749
- return await withSessionOperationLock(sessionWorkspace.session.sessionId, async () => {
1750
- const sandbox = await resolveProjectSandbox({ fleet, sandboxRow: sandboxBinding });
1751
- const access = await github.versionControl.getRepositoryAccess({
1752
- orgId,
1753
- repositoryId: project.repository.id
1754
- });
1755
- if (!access.authorization) throw new Error("Repository access did not include a bearer token.");
1756
- await pushBranch(sandbox, workdir, branch, access.authorization.token, project.repository.slug);
1757
- await emitAudit?.({
1758
- context: loose(c),
1759
- input: {
1760
- action: "factory.git.push",
1761
- factoryProjectId: project.factoryProjectId,
1762
- projectRepositoryId: project.id,
1763
- targets: [{ type: "branch", id: branch }],
1764
- metadata: { branch, sessionId: sessionWorkspace.session.sessionId }
1765
- }
1766
- });
1767
- return c.json({ pushed: true, branch });
1768
- });
1769
- } catch (err) {
1770
- return gitErrorResponse(loose(c), err);
1771
- }
1772
- }
1773
- }),
1774
- // ── Open a pull request through the version-control capability ─────────
1775
- registerApiRoute("/web/github/projects/:id/pr", {
1776
- method: "POST",
1777
- requiresAuth: false,
1778
- handler: async (c) => {
1779
- const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
1780
- if ("response" in owned) return owned.response;
1781
- const { orgId, userId, project } = owned;
1782
- let body;
1783
- try {
1784
- body = await c.req.json();
1785
- } catch {
1786
- return c.json({ error: "Invalid JSON body" }, 400);
1787
- }
1788
- if (!isValidGitRef(body.branch)) {
1789
- return c.json({ error: "Invalid branch" }, 400);
1790
- }
1791
- const base = body.base === void 0 ? project.defaultBranch : body.base;
1792
- if (!isValidGitRef(base)) {
1793
- return c.json({ error: "Invalid base" }, 400);
1794
- }
1795
- if (typeof body.title !== "string" || body.title.trim().length === 0 || body.title.length > 256) {
1796
- return c.json({ error: "Invalid title" }, 400);
1797
- }
1798
- if (body.body !== void 0 && (typeof body.body !== "string" || body.body.length > 65536)) {
1799
- return c.json({ error: "Invalid body" }, 400);
1800
- }
1801
- const head = body.branch;
1802
- const title = body.title;
1803
- const prBody = body.body;
1804
- const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
1805
- if (!sessionWorkspace) {
1806
- return c.json({ error: "Invalid sessionId" }, 400);
1807
- }
1808
- try {
1809
- return await withSessionOperationLock(sessionWorkspace.session.sessionId, async () => {
1810
- const result = await github.versionControl.createPullRequest({
1811
- connection: {
1812
- type: "app-installation",
1813
- installationId: Number(project.installation.externalId)
1814
- },
1815
- sourceId: project.repository.slug,
1816
- baseBranch: base,
1817
- headBranch: head,
1818
- title,
1819
- body: prBody,
1820
- actingUserId: userId
1821
- });
1822
- await emitAudit?.({
1823
- context: loose(c),
1824
- input: {
1825
- action: "factory.git.pr_opened",
1826
- factoryProjectId: project.factoryProjectId,
1827
- projectRepositoryId: project.id,
1828
- targets: [{ type: "pull_request", id: result.url, name: title }],
1829
- metadata: { branch: head, base, url: result.url }
1830
- }
1831
- });
1832
- const pullRequestNumber = pullRequestNumberFromUrl(result.url, project.repository.slug);
1833
- if (pullRequestNumber) {
1834
- const sessionId = sessionWorkspace.session.sessionId;
1835
- await subscribeToPullRequest(
1836
- {
1837
- orgId,
1838
- installationExternalId: project.installation.externalId,
1839
- projectRepositoryId: project.id,
1840
- repositoryExternalId: project.repository.externalId,
1841
- repositorySlug: project.repository.slug,
1842
- changeRequestId: pullRequestNumber.toString(),
1843
- sessionId,
1844
- ownerId: userId,
1845
- resourceId: sessionId,
1846
- threadId: sessionId,
1847
- source: "factory-pr-create",
1848
- subscribedByUserId: userId
1849
- },
1850
- github.integrationStorage
1851
- ).catch((error) => {
1852
- console.warn(
1853
- `[GitHub] Pull request ${result.url} was created but automatic subscription failed.`,
1854
- error
1855
- );
1856
- });
1857
- }
1858
- return c.json({ url: result.url });
1859
- });
1860
- } catch (err) {
1861
- return c.json(
1862
- { error: "github_pr_create_failed", message: err instanceof Error ? err.message : String(err) },
1863
- 502
1864
- );
1865
- }
1866
- }
1867
- }),
1868
- // ── Tear down the caller's sandbox for a project ────────────────────────
1869
- // Per-user teardown only: drops the caller's `(project, user)` sandbox
1870
- // binding and stops the VM, freeing a slot in the per-replica budget. Project
1871
- // deletion at the org level is out of scope (org admin model is later).
1872
- registerApiRoute("/web/github/projects/:id/sandbox", {
1873
- method: "DELETE",
1874
- requiresAuth: false,
1875
- handler: async (c) => {
1876
- const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
1877
- if ("response" in owned) return owned.response;
1878
- const { sandboxRow } = owned;
1879
- if (!sandboxRow.sandboxId) {
1880
- return c.json({ tornDown: false });
1881
- }
1882
- try {
1883
- return await withSessionOperationLock(`sandbox:${sandboxRow.id}`, async () => {
1884
- const sandbox = await fleet.reattachSandbox(sandboxRow.sandboxId);
1885
- await teardownProjectSandbox({
1886
- fleet,
1887
- row: sandboxRow,
1888
- storage: github.sourceControlStorage.sandboxes,
1889
- sandbox
1890
- });
1891
- return c.json({ tornDown: true });
1892
- });
1893
- } catch (err) {
1894
- return gitErrorResponse(loose(c), err);
1895
- }
1896
- }
1897
- })
1898
- ];
1899
- }
1900
- async function resolveSessionWorkspace(github, projectId, userId, sessionId) {
1901
- if (typeof sessionId !== "string") {
1902
- return void 0;
1903
- }
1904
- const session = await github.sourceControlStorage.sessions.getBySessionId(sessionId);
1905
- if (session?.projectRepositoryId !== projectId || session.userId !== userId || !session.sandboxId || !session.sandboxWorkdir) {
1906
- return void 0;
1907
- }
1908
- return {
1909
- session,
1910
- workdir: session.sandboxWorkdir,
1911
- sandboxBinding: {
1912
- id: session.id,
1913
- projectRepositoryId: session.projectRepositoryId,
1914
- userId: session.userId,
1915
- sandboxId: session.sandboxId,
1916
- sandboxWorkdir: session.sandboxWorkdir,
1917
- materializedAt: session.materializedAt,
1918
- createdAt: session.createdAt
1919
- }
1920
- };
1921
- }
1922
-
1923
- // src/rules/resolve.ts
1924
- function resolveFactoryGithubRule(rules, event) {
1925
- return rules.github[event]?.onEvent;
1926
- }
1927
-
1928
- // src/rules/types.ts
1929
- var FACTORY_RULE_STAGES = ["intake", "triage", "planning", "execute", "review", "done", "canceled"];
1930
- var FACTORY_RULE_BOARDS = ["work", "review"];
1931
-
1932
- // src/rules/validation.ts
1933
- var MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;
1934
- var MAX_IDEMPOTENCY_KEY_LENGTH = 256;
1935
- var MAX_REASON_LENGTH = 512;
1936
- var MAX_TITLE_LENGTH = 512;
1937
- var MAX_MESSAGE_LENGTH = 8192;
1938
- var MAX_ARGUMENTS_LENGTH = 4096;
1939
- var MAX_ROLE_LENGTH = 32;
1940
- var MAX_SKILL_NAME_LENGTH = 128;
1941
- var MAX_SOURCE_KEY_LENGTH = 256;
1942
- var MAX_URL_LENGTH = 2048;
1943
- var MAX_METADATA_JSON_LENGTH = 16384;
1944
- var MAX_JSON_DEPTH = 8;
1945
- var MAX_JSON_COLLECTION_SIZE = 100;
1946
- var IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;
1947
- var SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
1948
- var SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;
1949
- var WORK_ITEM_SOURCES = ["github-issue", "github-pr", "linear-issue", "manual"];
1950
- var REJECTION_CODES = [
1951
- "forbidden",
1952
- "invalid_transition",
1953
- "missing_binding",
1954
- "stale",
1955
- "timeout",
1956
- "rule_error",
1957
- "causal_depth_exceeded",
1958
- "repeated_transition"
1959
- ];
1960
- var FactoryRuleValidationError = class extends Error {
1961
- code = "invalid_factory_rule";
1962
- constructor(message) {
1963
- super(message);
1964
- this.name = "FactoryRuleValidationError";
1965
- }
1966
- };
1967
- function isPlainObject(value) {
1968
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1969
- const prototype = Object.getPrototypeOf(value);
1970
- return prototype === Object.prototype || prototype === null;
1971
- }
1972
- function assertExactKeys(value, keys, label) {
1973
- const allowed = new Set(keys);
1974
- if (Object.keys(value).some((key) => !allowed.has(key))) {
1975
- throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);
1976
- }
1977
- }
1978
- function boundedString(value, label, max, pattern) {
1979
- if (typeof value !== "string") throw new FactoryRuleValidationError(`${label} must be a string.`);
1980
- const normalized = value.trim();
1981
- if (normalized.length === 0 || normalized.length > max || pattern && !pattern.test(normalized)) {
1982
- throw new FactoryRuleValidationError(`${label} is invalid.`);
1983
- }
1984
- return normalized;
1985
- }
1986
- function optionalBoundedString(value, label, max) {
1987
- if (value === void 0) return void 0;
1988
- return boundedString(value, label, max);
1989
- }
1990
- function enumValue(value, allowed, label) {
1991
- if (typeof value !== "string" || !allowed.includes(value)) {
1992
- throw new FactoryRuleValidationError(`${label} is invalid.`);
1993
- }
1994
- return value;
1995
- }
1996
- function normalizeFactoryRuleJsonValue(value, depth = 0, seen = /* @__PURE__ */ new Set()) {
1997
- if (value === null || typeof value === "boolean" || typeof value === "string") return value;
1998
- if (typeof value === "number") {
1999
- if (!Number.isFinite(value)) throw new FactoryRuleValidationError("Rule metadata must contain finite numbers.");
2000
- return value;
2001
- }
2002
- if (depth >= MAX_JSON_DEPTH || typeof value !== "object" && !Array.isArray(value)) {
2003
- throw new FactoryRuleValidationError("Rule metadata is not bounded JSON.");
2004
- }
2005
- if (seen.has(value)) throw new FactoryRuleValidationError("Rule metadata must not contain cycles.");
2006
- seen.add(value);
2007
- try {
2008
- if (Array.isArray(value)) {
2009
- if (value.length > MAX_JSON_COLLECTION_SIZE) {
2010
- throw new FactoryRuleValidationError("Rule metadata contains too many entries.");
2011
- }
2012
- return value.map((entry) => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));
2013
- }
2014
- if (!isPlainObject(value)) throw new FactoryRuleValidationError("Rule metadata must use plain objects.");
2015
- const entries = Object.entries(value);
2016
- if (entries.length > MAX_JSON_COLLECTION_SIZE) {
2017
- throw new FactoryRuleValidationError("Rule metadata contains too many fields.");
2018
- }
2019
- const sanitized = {};
2020
- for (const [key, entry] of entries) {
2021
- const normalizedKey = boundedString(key, "Rule metadata key", 128, IDENTIFIER_RE);
2022
- sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey) ? "[REDACTED]" : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);
2023
- }
2024
- return sanitized;
2025
- } finally {
2026
- seen.delete(value);
2027
- }
2028
- }
2029
- function sanitizeMetadata(value) {
2030
- if (value === void 0) return void 0;
2031
- const sanitized = normalizeFactoryRuleJsonValue(value);
2032
- if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError("Rule metadata must be an object.");
2033
- if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {
2034
- throw new FactoryRuleValidationError("Rule metadata is too large.");
2035
- }
2036
- return sanitized;
2037
- }
2038
- function commonCommitFields(value) {
2039
- return {
2040
- idempotencyKey: boundedString(value.idempotencyKey, "Factory decision idempotencyKey", MAX_IDEMPOTENCY_KEY_LENGTH)
2041
- };
2042
- }
2043
- function validateFactoryRuleDecision(value, causalDepth = 0) {
2044
- if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {
2045
- throw new FactoryRuleValidationError("Factory rule causal depth exceeded.");
2046
- }
2047
- if (!isPlainObject(value)) throw new FactoryRuleValidationError("Factory rule decision must be an object.");
2048
- const type = value.type;
2049
- if (typeof type !== "string") throw new FactoryRuleValidationError("Factory rule decision type is required.");
2050
- switch (type) {
2051
- case "reject": {
2052
- assertExactKeys(value, ["type", "code", "reason"], "Factory reject decision");
2053
- return {
2054
- type,
2055
- code: enumValue(value.code, REJECTION_CODES, "Factory rejection code"),
2056
- reason: boundedString(value.reason, "Factory rejection reason", MAX_REASON_LENGTH)
2057
- };
2058
- }
2059
- case "transition": {
2060
- assertExactKeys(value, ["type", "idempotencyKey", "board", "stage"], "Factory transition decision");
2061
- return {
2062
- type,
2063
- ...commonCommitFields(value),
2064
- board: enumValue(value.board, FACTORY_RULE_BOARDS, "Factory transition board"),
2065
- stage: enumValue(value.stage, FACTORY_RULE_STAGES, "Factory transition stage")
2066
- };
2067
- }
2068
- case "upsertLinkedWorkItem": {
2069
- assertExactKeys(
2070
- value,
2071
- ["type", "idempotencyKey", "board", "source", "sourceKey", "title", "url", "stage", "metadata"],
2072
- "Factory linked work item decision"
2073
- );
2074
- const url = value.url;
2075
- if (url !== null && (typeof url !== "string" || url.length > MAX_URL_LENGTH || !/^https?:\/\//.test(url))) {
2076
- throw new FactoryRuleValidationError("Factory linked work item URL is invalid.");
2077
- }
2078
- const metadata = sanitizeMetadata(value.metadata);
2079
- return {
2080
- type,
2081
- ...commonCommitFields(value),
2082
- board: enumValue(value.board, FACTORY_RULE_BOARDS, "Factory linked work item board"),
2083
- source: enumValue(value.source, WORK_ITEM_SOURCES, "Factory linked work item source"),
2084
- sourceKey: boundedString(value.sourceKey, "Factory linked work item sourceKey", MAX_SOURCE_KEY_LENGTH),
2085
- title: boundedString(value.title, "Factory linked work item title", MAX_TITLE_LENGTH),
2086
- url,
2087
- stage: enumValue(value.stage, FACTORY_RULE_STAGES, "Factory linked work item stage"),
2088
- ...metadata ? { metadata } : {}
2089
- };
2090
- }
2091
- case "invokeSkill": {
2092
- assertExactKeys(
2093
- value,
2094
- ["type", "idempotencyKey", "role", "skillName", "arguments", "precedingMessage"],
2095
- "Factory invoke skill decision"
2096
- );
2097
- const args = optionalBoundedString(value.arguments, "Factory skill arguments", MAX_ARGUMENTS_LENGTH);
2098
- const precedingMessage = optionalBoundedString(
2099
- value.precedingMessage,
2100
- "Factory skill preceding message",
2101
- MAX_MESSAGE_LENGTH
2102
- );
2103
- return {
2104
- type,
2105
- ...commonCommitFields(value),
2106
- role: boundedString(value.role, "Factory skill role", MAX_ROLE_LENGTH, IDENTIFIER_RE),
2107
- skillName: boundedString(value.skillName, "Factory skill name", MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),
2108
- ...args ? { arguments: args } : {},
2109
- ...precedingMessage ? { precedingMessage } : {}
2110
- };
2111
- }
2112
- case "sendMessage": {
2113
- assertExactKeys(
2114
- value,
2115
- ["type", "idempotencyKey", "role", "message", "priority", "idleBehavior", "prepareBinding"],
2116
- "Factory send message decision"
2117
- );
2118
- const priority = value.priority === void 0 ? void 0 : enumValue(value.priority, ["medium", "high", "urgent"], "Factory message priority");
2119
- const idleBehavior = value.idleBehavior === void 0 ? void 0 : enumValue(value.idleBehavior, ["persist", "wake"], "Factory message idle behavior");
2120
- if (value.prepareBinding !== void 0 && typeof value.prepareBinding !== "boolean") {
2121
- throw new FactoryRuleValidationError("Factory message prepareBinding must be a boolean.");
2122
- }
2123
- return {
2124
- type,
2125
- ...commonCommitFields(value),
2126
- role: boundedString(value.role, "Factory message role", MAX_ROLE_LENGTH, IDENTIFIER_RE),
2127
- message: boundedString(value.message, "Factory message", MAX_MESSAGE_LENGTH),
2128
- ...priority ? { priority } : {},
2129
- ...idleBehavior ? { idleBehavior } : {},
2130
- ...value.prepareBinding === true ? { prepareBinding: true } : {}
2131
- };
2132
- }
2133
- case "notify": {
2134
- assertExactKeys(value, ["type", "idempotencyKey", "title", "body", "level"], "Factory notify decision");
2135
- const body = optionalBoundedString(value.body, "Factory notification body", MAX_MESSAGE_LENGTH);
2136
- const level = value.level === void 0 ? void 0 : enumValue(value.level, ["info", "warning", "error"], "Factory notification level");
2137
- return {
2138
- type,
2139
- ...commonCommitFields(value),
2140
- title: boundedString(value.title, "Factory notification title", MAX_TITLE_LENGTH),
2141
- ...body ? { body } : {},
2142
- ...level ? { level } : {}
2143
- };
2144
- }
2145
- default:
2146
- throw new FactoryRuleValidationError("Factory rule decision type is unsupported.");
2147
- }
2148
- }
2149
- function validateFactoryRuleDecisions(values, causalDepth = 0) {
2150
- if (values.length > MAX_JSON_COLLECTION_SIZE) {
2151
- throw new FactoryRuleValidationError("Factory rule produced too many decisions.");
2152
- }
2153
- const decisions = [];
2154
- for (const value of values) {
2155
- const decision = validateFactoryRuleDecision(value, causalDepth);
2156
- if (decision.type === "reject") {
2157
- throw new FactoryRuleValidationError("A rejection cannot be persisted with commit decisions.");
2158
- }
2159
- decisions.push(decision);
2160
- }
2161
- const keys = decisions.map((decision) => decision.idempotencyKey);
2162
- if (new Set(keys).size !== keys.length) {
2163
- throw new FactoryRuleValidationError("Factory decisions require unique idempotency keys.");
2164
- }
2165
- return decisions;
2166
- }
2167
-
2168
- // src/integrations/github/rules.ts
2169
- var TRUSTED_PERMISSIONS = /* @__PURE__ */ new Set(["write", "admin"]);
2170
- var RULE_TIMEOUT_MS = 5e3;
2171
- async function withRuleTimeout(promise) {
2172
- let timeout;
2173
- try {
2174
- return await Promise.race([
2175
- promise,
2176
- new Promise((_, reject) => {
2177
- timeout = setTimeout(() => reject(new Error("FACTORY_RULE_TIMEOUT")), RULE_TIMEOUT_MS);
2178
- })
2179
- ]);
2180
- } finally {
2181
- if (timeout) clearTimeout(timeout);
2182
- }
2183
- }
2184
- function object(value) {
2185
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2186
- }
2187
- function string(value) {
2188
- return typeof value === "string" && value.length > 0 ? value : void 0;
2189
- }
2190
- function number(value) {
2191
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2192
- }
2193
- function boolean(value) {
2194
- return typeof value === "boolean" ? value : void 0;
2195
- }
2196
- function eventName(parsed) {
2197
- const action = string(parsed.payload.action);
2198
- if (parsed.event === "issues" && action === "opened") return "issueOpened";
2199
- if (parsed.event === "pull_request" && action === "opened") return "pullRequestOpened";
2200
- if (parsed.event === "pull_request" && action === "synchronize") return "pullRequestUpdated";
2201
- if (parsed.event === "pull_request" && action === "closed" && boolean(object(parsed.payload.pull_request)?.merged)) {
2202
- return "pullRequestMerged";
2203
- }
2204
- if (parsed.event === "pull_request" && action === "review_requested") return "pullRequestReviewRequested";
2205
- return void 0;
2206
- }
2207
- function canonicalSourceKey(kind, itemNumber) {
2208
- return kind === "issue" ? `github-issue:${itemNumber}` : `github-pr:${itemNumber}`;
2209
- }
2210
- function legacySourceKey(repositoryId, kind, itemNumber) {
2211
- return `github:${repositoryId}:${kind}:${itemNumber}`;
2212
- }
2213
- function provenanceTarget(repositoryId, pullRequestNumber) {
2214
- return `factory-pr-provenance:${repositoryId}:${pullRequestNumber}`;
2215
- }
2216
- function workItemSource(item) {
2217
- if (!item.externalSource) return "manual";
2218
- return item.externalSource.type === "pull-request" ? "github-pr" : "github-issue";
2219
- }
2220
- function workItemSourceKey(item) {
2221
- return item.externalSource?.externalId ?? null;
2222
- }
2223
- async function githubActor(github, input) {
2224
- let trusted = false;
2225
- try {
2226
- const permission = await github.getRepositoryCollaboratorPermission(
2227
- input.installationId,
2228
- input.repository,
2229
- input.login
2230
- );
2231
- trusted = permission !== void 0 && TRUSTED_PERMISSIONS.has(permission);
2232
- } catch {
2233
- trusted = false;
2234
- }
2235
- return { type: "github", login: input.login, trusted, factoryAuthored: input.factoryAuthored };
2236
- }
2237
- function pullRequestProvenance(data) {
2238
- if (!data || data.kind !== "factory-pr-provenance" || typeof data.workItemId !== "string") return null;
2239
- return { kind: "factory-pr-provenance", workItemId: data.workItemId };
2240
- }
2241
- var GithubRules = class {
2242
- constructor(options) {
2243
- this.options = options;
2244
- }
2245
- options;
2246
- async ingest(parsed) {
2247
- const event = eventName(parsed);
2248
- const repository = object(parsed.payload.repository);
2249
- const installationId = number(object(parsed.payload.installation)?.id);
2250
- const repositoryId = number(repository?.id);
2251
- const repositoryName = string(repository?.full_name);
2252
- const login = string(object(parsed.payload.sender)?.login);
2253
- if (!event || !installationId || !repositoryId || !repositoryName || !login) return { status: "ignored" };
2254
- const projects = await this.options.sourceControl.projectRepositories.listByExternalRepository({
2255
- installationExternalId: String(installationId),
2256
- repositoryExternalId: String(repositoryId)
2257
- });
2258
- if (projects.length === 0) return { status: "ignored" };
2259
- const results = [];
2260
- for (const project of projects) {
2261
- results.push(
2262
- await this.#ingestProject(parsed, event, installationId, repositoryId, repositoryName, login, project)
2263
- );
2264
- }
2265
- if (results.some((result) => result.status === "committed")) return { status: "committed" };
2266
- if (results.some((result) => result.status === "replayed")) return { status: "replayed" };
2267
- return results[0] ?? { status: "ignored" };
2268
- }
2269
- async #ingestProject(parsed, event, installationId, repositoryId, repositoryName, login, project) {
2270
- const factoryProject = await this.options.projects.get({
2271
- orgId: project.orgId,
2272
- id: project.factoryProjectId
2273
- });
2274
- if (!factoryProject) return { status: "missing" };
2275
- const issue = object(parsed.payload.issue);
2276
- const pullRequest = object(parsed.payload.pull_request);
2277
- const issueNumber = number(issue?.number);
2278
- const pullRequestNumber = number(pullRequest?.number);
2279
- const provenance = pullRequestNumber ? pullRequestProvenance(
2280
- (await this.options.integrationStorage.subscriptions.listByTarget(
2281
- provenanceTarget(repositoryId, pullRequestNumber),
2282
- { status: "active" }
2283
- )).find((subscription) => subscription.orgId === project.orgId)?.data
2284
- ) : null;
2285
- const relatedItem = await this.#relatedItem(
2286
- project.orgId,
2287
- project.factoryProjectId,
2288
- repositoryId,
2289
- issueNumber,
2290
- pullRequestNumber,
2291
- string(object(pullRequest?.head)?.ref),
2292
- provenance
2293
- );
2294
- const actor = await githubActor(this.options.github, {
2295
- installationId,
2296
- repository: repositoryName,
2297
- login,
2298
- factoryAuthored: provenance !== null
2299
- });
2300
- const context = {
2301
- tenant: { orgId: project.orgId, projectId: project.factoryProjectId },
2302
- actor,
2303
- ingress: { type: "github", id: `${installationId}:${parsed.deliveryId}` },
2304
- cause: `github.${event}`,
2305
- causalChain: [],
2306
- ruleSetVersion: this.options.rules.version,
2307
- ...relatedItem ? {
2308
- item: {
2309
- id: relatedItem.id,
2310
- source: workItemSource(relatedItem),
2311
- sourceKey: workItemSourceKey(relatedItem),
2312
- parentWorkItemId: relatedItem.parentWorkItemId,
2313
- title: relatedItem.title,
2314
- url: relatedItem.externalSource?.url ?? null,
2315
- stages: relatedItem.stages
2316
- },
2317
- board: relatedItem.externalSource?.type === "pull-request" ? "review" : "work",
2318
- itemRevision: relatedItem.revision
2319
- } : {},
2320
- event,
2321
- deliveryId: parsed.deliveryId,
2322
- factory: { createdAt: factoryProject.createdAt.toISOString() },
2323
- repository: { id: repositoryId, fullName: repositoryName },
2324
- ...issueNumber && string(issue?.title) && string(issue?.html_url) ? {
2325
- issue: {
2326
- number: issueNumber,
2327
- title: string(issue?.title),
2328
- url: string(issue?.html_url),
2329
- ...string(issue?.created_at) ? { createdAt: string(issue?.created_at) } : {}
2330
- }
2331
- } : {},
2332
- ...pullRequestNumber && string(pullRequest?.title) && string(pullRequest?.html_url) ? {
2333
- pullRequest: {
2334
- number: pullRequestNumber,
2335
- title: string(pullRequest?.title),
2336
- url: string(pullRequest?.html_url),
2337
- ...string(pullRequest?.created_at) ? { createdAt: string(pullRequest?.created_at) } : {},
2338
- state: string(pullRequest?.state) === "closed" ? "closed" : "open",
2339
- merged: boolean(pullRequest?.merged) ?? false,
2340
- headBranch: string(object(pullRequest?.head)?.ref) ?? "",
2341
- baseBranch: string(object(pullRequest?.base)?.ref) ?? ""
2342
- }
2343
- } : {},
2344
- ...object(parsed.payload.review) ? {
2345
- review: {
2346
- id: number(object(parsed.payload.review)?.id) ?? 0,
2347
- state: string(object(parsed.payload.review)?.state) ?? "unknown",
2348
- url: string(object(parsed.payload.review)?.html_url) ?? ""
2349
- }
2350
- } : {}
2351
- };
2352
- const rule = resolveFactoryGithubRule(this.options.rules, event);
2353
- let decision;
2354
- let decisions = [];
2355
- let outcome = { status: "accepted" };
2356
- try {
2357
- decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : void 0;
2358
- if (decision?.type === "reject") {
2359
- outcome = { status: "rejected", code: decision.code, reason: decision.reason };
2360
- } else if (decision) {
2361
- decisions = validateFactoryRuleDecisions([decision]).map((entry) => ({ ...entry }));
2362
- }
2363
- } catch (error) {
2364
- const timedOut = error instanceof Error && error.message === "FACTORY_RULE_TIMEOUT";
2365
- outcome = {
2366
- status: "rejected",
2367
- code: timedOut ? "timeout" : "rule_error",
2368
- reason: timedOut ? "Factory rule evaluation timed out." : error instanceof Error ? error.message.slice(0, 2e3) : "Factory GitHub rule failed."
2369
- };
2370
- }
2371
- const committed = await this.options.storage.commitRuleEvaluation({
2372
- orgId: project.orgId,
2373
- factoryProjectId: project.factoryProjectId,
2374
- workItemId: relatedItem?.id ?? null,
2375
- ingress: { identity: `${installationId}:${parsed.deliveryId}`, triggerType: `github.${event}` },
2376
- ruleSetVersion: this.options.rules.version,
2377
- expectedRevision: relatedItem?.revision ?? null,
2378
- actor: { ...actor },
2379
- outcome,
2380
- decisions,
2381
- causalChain: [],
2382
- now: /* @__PURE__ */ new Date()
2383
- });
2384
- return { status: committed.status };
2385
- }
2386
- async #relatedItem(orgId, projectId, repositoryId, issueNumber, pullRequestNumber, pullRequestHeadBranch, provenance) {
2387
- const items = await this.options.storage.list({ orgId, factoryProjectId: projectId });
2388
- if (provenance) return items.find((item) => item.id === provenance.workItemId);
2389
- if (issueNumber) {
2390
- return items.find((item) => item.externalSource?.externalId === canonicalSourceKey("issue", issueNumber)) ?? items.find((item) => item.externalSource?.externalId === legacySourceKey(repositoryId, "issue", issueNumber));
2391
- }
2392
- if (pullRequestNumber) {
2393
- return items.find((item) => item.externalSource?.externalId === canonicalSourceKey("pull-request", pullRequestNumber)) ?? items.find(
2394
- (item) => item.externalSource?.externalId === legacySourceKey(repositoryId, "pull-request", pullRequestNumber)
2395
- ) ?? // Provenance fallback: a PR pushed from a work item's session branch
2396
- // belongs to that item even when no gh-pr-create provenance was
2397
- // recorded (session predating state seeding, or the PR was opened
2398
- // outside the tracked tool call). Session branches are per-item
2399
- // (`factory/issue-N`), so a head-branch match is unambiguous.
2400
- (pullRequestHeadBranch ? items.find(
2401
- (item) => item.externalSource?.type !== "pull-request" && Object.values(item.sessions).some((session) => session.branch === pullRequestHeadBranch)
2402
- ) : void 0);
2403
- }
2404
- return void 0;
2405
- }
2406
- };
2407
- function attachGithubRules(github, context) {
2408
- if (!context.rules) return void 0;
2409
- const rules = new GithubRules({
2410
- github,
2411
- sourceControl: context.storage.sourceControl,
2412
- integrationStorage: context.storage.generic,
2413
- projects: context.storage.projects,
2414
- storage: context.rules.workItems,
2415
- rules: context.rules.config
2416
- });
2417
- return (event) => rules.ingest(event);
2418
- }
2419
-
2420
- // src/integrations/github/session-subscriptions.ts
2421
- import { createTool } from "@mastra/core/tools";
2422
- import { z } from "zod";
2423
-
2424
- // src/integrations/github/token-refresh.ts
2425
- var GITHUB_TOKEN_INJECTOR_CONTEXT_KEY = "factoryGithubTokenInjector";
2426
- var GITHUB_PAT_KIND_CONTEXT_KEY = "factoryGithubPatKind";
2427
- function getRegisteredGithubPatKind(requestContext) {
2428
- const kind = requestContext.get(GITHUB_PAT_KIND_CONTEXT_KEY);
2429
- return kind === "reviewer" ? "reviewer" : "default";
2430
- }
2431
- function injectGithubToken(requestContext, token) {
2432
- const injector = requestContext.get(GITHUB_TOKEN_INJECTOR_CONTEXT_KEY);
2433
- if (!injector) {
2434
- throw new Error("GitHub token refresh requires an active Factory sandbox workspace.");
2435
- }
2436
- injector(token);
2437
- }
2438
-
2439
- // src/integrations/github/session-subscriptions.ts
2440
- function sessionUserId(user) {
2441
- return user?.workosId ?? user?.id;
2442
- }
2443
- function sessionOrgId(user) {
2444
- return user?.organizationId;
2445
- }
2446
- var pullRequestInputSchema = z.object({
2447
- pullRequest: z.union([z.number().int().positive(), z.string().min(1)])
2448
- });
2449
- function parsePullRequest(value, expectedRepo) {
2450
- if (typeof value === "number") return value;
2451
- if (/^\d+$/.test(value)) return Number(value);
2452
- const match = value.match(/^https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)\/?$/i);
2453
- if (!match || match[1].toLowerCase() !== expectedRepo.toLowerCase()) {
2454
- throw new Error(`Pull request must belong to ${expectedRepo}.`);
2455
- }
2456
- return Number(match[2]);
2457
- }
2458
- function isGithubProjectSession(requestContext) {
2459
- const context = requestContext.get("controller");
2460
- const user = requestContext.get("user");
2461
- return Boolean(
2462
- context?.threadId && context.getState().projectRepositoryId && sessionOrgId(user) && sessionUserId(user)
2463
- );
2464
- }
2465
- async function resolveSessionTarget(requestContext, github) {
2466
- const context = requestContext.get("controller");
2467
- const user = requestContext.get("user");
2468
- const orgId = sessionOrgId(user);
2469
- const userId = sessionUserId(user);
2470
- const projectRepositoryId = context?.getState().projectRepositoryId;
2471
- if (!context || !context.threadId || !projectRepositoryId || !orgId || !userId) {
2472
- throw new Error("GitHub subscriptions require an authenticated repository session with an active thread.");
2473
- }
2474
- const projectRepository = await github.sourceControlStorage.projectRepositories.get({
2475
- orgId,
2476
- id: projectRepositoryId
2477
- });
2478
- if (!projectRepository) throw new Error("Project repository not found for this organization.");
2479
- const connection = await github.sourceControlStorage.connections.get({ orgId, id: projectRepository.connectionId });
2480
- if (!connection) throw new Error("Source-control connection not found for this organization.");
2481
- const repository = await github.sourceControlStorage.repositories.get({ orgId, id: projectRepository.repositoryId });
2482
- if (!repository) throw new Error("Repository not found for this organization.");
2483
- const installation = await github.sourceControlStorage.installations.get({ orgId, id: connection.installationId });
2484
- if (!installation) throw new Error("Source-control installation not found for this organization.");
2485
- return { context, projectRepository, connection, installation, repository, orgId, userId };
2486
- }
2487
- async function verifyPullRequest(target, pullRequest, github) {
2488
- const [owner, repo] = target.repository.slug.split("/");
2489
- if (!owner || !repo) throw new Error("GitHub repository is invalid.");
2490
- const octokit = github.getInstallationOctokit(Number(target.installation.externalId));
2491
- const { data } = await octokit.pulls.get({ owner, repo, pull_number: pullRequest });
2492
- if (String(data.base.repo.id) !== target.repository.externalId)
2493
- throw new Error("Pull request repository does not match the active project repository.");
2494
- }
2495
- async function subscriptionInput(target, pullRequestNumber) {
2496
- return {
2497
- orgId: target.orgId,
2498
- installationExternalId: target.installation.externalId,
2499
- projectRepositoryId: target.projectRepository.id,
2500
- repositoryExternalId: target.repository.externalId,
2501
- repositorySlug: target.repository.slug,
2502
- changeRequestId: String(pullRequestNumber),
2503
- sessionId: target.context.session.id,
2504
- ownerId: target.context.session.ownerId,
2505
- resourceId: target.connection.factoryProjectId,
2506
- threadId: target.context.threadId,
2507
- sessionScope: target.context.scope,
2508
- source: "explicit-tool",
2509
- subscribedByUserId: target.userId
2510
- };
2511
- }
2512
- async function subscribeCurrentSessionToPullRequest(requestContext, pullRequest, source, github) {
2513
- if (source === "auto-gh-pr-create" && !isGithubProjectSession(requestContext)) return void 0;
2514
- const target = await resolveSessionTarget(requestContext, github);
2515
- const number2 = parsePullRequest(pullRequest, target.repository.slug);
2516
- await verifyPullRequest(target, number2, github);
2517
- await subscribeToPullRequest({ ...await subscriptionInput(target, number2), source }, github.integrationStorage);
2518
- return number2;
2519
- }
2520
- async function unsubscribeCurrentSessionFromPullRequest(requestContext, pullRequest, github) {
2521
- const target = await resolveSessionTarget(requestContext, github);
2522
- const number2 = parsePullRequest(pullRequest, target.repository.slug);
2523
- await unsubscribeFromPullRequest(await subscriptionInput(target, number2), github.integrationStorage);
2524
- return number2;
2525
- }
2526
- async function refreshGithubToken(requestContext, github) {
2527
- const target = await resolveSessionTarget(requestContext, github);
2528
- const pat = await getGithubPat(
2529
- () => github.integrationStorage,
2530
- target.orgId,
2531
- getRegisteredGithubPatKind(requestContext)
2532
- );
2533
- if (pat) {
2534
- injectGithubToken(requestContext, pat);
2535
- return;
2536
- }
2537
- const access = await github.versionControl.getRepositoryAccess({
2538
- orgId: target.orgId,
2539
- repositoryId: target.repository.id
2540
- });
2541
- const token = access.authorization?.token;
2542
- if (!token) throw new Error("Repository access did not include a bearer token for the Factory session.");
2543
- injectGithubToken(requestContext, token);
2544
- }
2545
- function createGithubSubscriptionTools(requestContext, github) {
2546
- const context = requestContext.get("controller");
2547
- const user = requestContext.get("user");
2548
- if (!context?.getState().projectRepositoryId || !sessionOrgId(user) || !sessionUserId(user)) return {};
2549
- return {
2550
- github_refresh_token: createTool({
2551
- id: "github_refresh_token",
2552
- description: "Refresh GitHub CLI authentication in the active Factory sandbox. Use this after a gh command fails because authentication is expired, invalid, or missing. It installs a fresh GH_TOKEN for subsequent sandbox commands. After this tool succeeds, retry the failed gh command. Takes no arguments and never returns the token.",
2553
- inputSchema: z.object({}),
2554
- execute: async () => {
2555
- await refreshGithubToken(requestContext, github);
2556
- return { refreshed: true };
2557
- }
2558
- }),
2559
- github_subscribe_pr: createTool({
2560
- id: "github_subscribe_pr",
2561
- description: "Subscribe this thread to GitHub pull request activity. You usually do not need this tool: successful gh pr create commands subscribe automatically. Use it for an existing PR or to recover when automatic subscription did not occur. Closed or merged PRs are unsubscribed automatically. Accepts a PR number or canonical URL for the active project.",
2562
- inputSchema: pullRequestInputSchema,
2563
- execute: async ({ pullRequest }) => {
2564
- const number2 = await subscribeCurrentSessionToPullRequest(requestContext, pullRequest, "explicit-tool", github);
2565
- return { subscribed: true, pullRequestNumber: number2 };
2566
- }
2567
- }),
2568
- github_unsubscribe_pr: createTool({
2569
- id: "github_unsubscribe_pr",
2570
- description: "Manually unsubscribe this thread from GitHub pull request activity. You usually do not need this tool because closed or merged PRs are unsubscribed automatically. Use it to stop notifications before then. Accepts a PR number or canonical URL for the active project.",
2571
- inputSchema: pullRequestInputSchema,
2572
- execute: async ({ pullRequest }) => {
2573
- const number2 = await unsubscribeCurrentSessionFromPullRequest(requestContext, pullRequest, github);
2574
- return { subscribed: false, pullRequestNumber: number2 };
2575
- }
2576
- })
2577
- };
2578
- }
2579
- function stripHeredocBodies(command) {
2580
- const lines = command.split("\n");
2581
- const executableLines = [];
2582
- let delimiter;
2583
- for (const line of lines) {
2584
- if (delimiter) {
2585
- if (line.trim() === delimiter) delimiter = void 0;
2586
- continue;
2587
- }
2588
- executableLines.push(line);
2589
- const heredoc = line.match(/<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/);
2590
- delimiter = heredoc?.[2];
2591
- }
2592
- return executableLines.join("\n");
2593
- }
2594
- function parseCreatedPullRequest(context) {
2595
- if (context.toolName !== "execute_command" || context.error) return void 0;
2596
- const command = context.input?.command;
2597
- if (typeof command !== "string" || !/(?:^|\n|;|&&|\|\|)\s*gh\s+pr\s+create(?:\s|$)/.test(stripHeredocBodies(command))) {
2598
- return void 0;
2599
- }
2600
- const output = context.output;
2601
- const stdout = typeof context.output === "string" ? context.output : output?.stdout ?? output?.result;
2602
- if (typeof stdout !== "string") return void 0;
2603
- const urls = stdout.match(/https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/\d+/g) ?? [];
2604
- return urls.length === 1 ? urls[0] : void 0;
2605
- }
2606
-
2607
- // src/integrations/platform/api-client.ts
2608
- function platformApiClientConfigFromEnv() {
2609
- const sharedApiUrl = process.env.MASTRA_SHARED_API_URL?.trim() || "https://platform.mastra.ai/v1";
2610
- const accessToken = process.env.MASTRA_PLATFORM_SECRET_KEY?.trim();
2611
- if (!accessToken) {
2612
- throw new Error("Platform integration: missing required environment variable MASTRA_PLATFORM_SECRET_KEY.");
2613
- }
2614
- return { baseUrl: normalizeSharedApiUrl(sharedApiUrl), accessToken };
2615
- }
2616
- function normalizeSharedApiUrl(sharedApiUrl) {
2617
- return sharedApiUrl.replace(/\/+$/, "").replace(/\/v1$/, "");
2618
- }
2619
- var PlatformApiError = class extends Error {
2620
- status;
2621
- retryAfterSeconds;
2622
- constructor(message, status, retryAfterSeconds = null) {
2623
- super(message);
2624
- this.name = "PlatformApiError";
2625
- this.status = status;
2626
- this.retryAfterSeconds = retryAfterSeconds;
2627
- }
2628
- };
2629
- var PlatformApiClient = class {
2630
- #baseUrl;
2631
- #accessToken;
2632
- #fetch;
2633
- constructor(config) {
2634
- const missing = ["baseUrl", "accessToken"].filter((field) => !config[field]);
2635
- if (missing.length > 0) {
2636
- throw new Error(`Platform integration: missing required config field(s): ${missing.join(", ")}.`);
2637
- }
2638
- this.#baseUrl = config.baseUrl.replace(/\/+$/, "");
2639
- this.#accessToken = config.accessToken;
2640
- this.#fetch = config.fetchImpl ?? globalThis.fetch;
2641
- }
2642
- async request(method, path2, body, options) {
2643
- const response = await this.#send(method, path2, body, options);
2644
- if (!response.ok) {
2645
- const message = redact(await extractError(response), this.#accessToken);
2646
- const retryAfterSeconds = parseRetryAfter(response.headers.get("retry-after"));
2647
- logPlatformError("Platform API request failed", {
2648
- method,
2649
- path: path2,
2650
- status: response.status,
2651
- retryAfterSeconds,
2652
- message
2653
- });
2654
- throw new PlatformApiError(message, response.status, retryAfterSeconds);
2655
- }
2656
- if (response.status === 204) return void 0;
2657
- return await response.json();
2658
- }
2659
- async requestRedirect(method, path2, options) {
2660
- const response = await this.#send(method, path2, void 0, options, "manual");
2661
- if (response.status >= 300 && response.status < 400) {
2662
- const location = response.headers.get("location");
2663
- if (location) return location;
2664
- }
2665
- if (!response.ok) {
2666
- const message = redact(await extractError(response), this.#accessToken);
2667
- const retryAfterSeconds = parseRetryAfter(response.headers.get("retry-after"));
2668
- logPlatformError("Platform API redirect request failed", {
2669
- method,
2670
- path: path2,
2671
- status: response.status,
2672
- retryAfterSeconds,
2673
- message
2674
- });
2675
- throw new PlatformApiError(message, response.status, retryAfterSeconds);
2676
- }
2677
- logPlatformError("Platform API request did not return a redirect", { method, path: path2, status: response.status });
2678
- throw new PlatformApiError("Platform API request did not return a redirect.", response.status);
2679
- }
2680
- async #send(method, path2, body, options, redirect) {
2681
- const headers = {
2682
- accept: "application/json",
2683
- authorization: `Bearer ${this.#accessToken}`
2684
- };
2685
- if (options?.actingUserId) {
2686
- headers["x-acting-user-id"] = options.actingUserId;
2687
- }
2688
- const timeoutSignal = AbortSignal.timeout(15e3);
2689
- const init = {
2690
- method,
2691
- headers,
2692
- redirect,
2693
- signal: options?.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal
2694
- };
2695
- if (body !== void 0) {
2696
- headers["content-type"] = "application/json";
2697
- init.body = JSON.stringify(body);
2698
- }
2699
- try {
2700
- return await this.#fetch(`${this.#baseUrl}${path2}`, init);
2701
- } catch (error) {
2702
- if (error instanceof Error && error.message.includes(this.#accessToken)) {
2703
- const redacted = new Error(redact(error.message, this.#accessToken));
2704
- redacted.name = error.name;
2705
- logPlatformError("Platform API transport error", {
2706
- method,
2707
- path: path2,
2708
- name: redacted.name,
2709
- message: redacted.message
2710
- });
2711
- throw redacted;
2712
- }
2713
- logPlatformError("Platform API transport error", {
2714
- method,
2715
- path: path2,
2716
- name: error instanceof Error ? error.name : void 0,
2717
- message: error instanceof Error ? error.message : String(error)
2718
- });
2719
- throw error;
2720
- }
2721
- }
2722
- };
2723
- async function extractError(response) {
2724
- try {
2725
- const data = await response.clone().json();
2726
- for (const field of ["detail", "error", "title"]) {
2727
- if (typeof data[field] === "string" && data[field]) return data[field];
2728
- }
2729
- } catch {
2730
- }
2731
- return `Platform API request failed (${response.status})`;
2732
- }
2733
- function redact(message, accessToken) {
2734
- return message.split(accessToken).join("[REDACTED]");
2735
- }
2736
- function logPlatformInfo(message, fields) {
2737
- writePlatformLog("info", message, fields);
2738
- }
2739
- function logPlatformWarn(message, fields) {
2740
- writePlatformLog("warn", message, fields);
2741
- }
2742
- function logPlatformError(message, fields) {
2743
- writePlatformLog("error", message, fields);
2744
- }
2745
- function writePlatformLog(level, message, fields) {
2746
- const metadata = fields ? ` ${JSON.stringify(stripUndefined(fields))}` : "";
2747
- process.stderr.write(`[Mastra Factory] ${level.toUpperCase()} ${message}${metadata}
2748
- `);
2749
- }
2750
- function stripUndefined(fields) {
2751
- return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0));
2752
- }
2753
- function parseRetryAfter(value) {
2754
- if (!value) return null;
2755
- const seconds = Number.parseInt(value, 10);
2756
- return Number.isSafeInteger(seconds) && seconds >= 0 ? seconds : null;
2757
- }
2758
-
2759
- // src/integrations/platform/github/event-worker.ts
2760
- import { randomUUID as randomUUID2 } from "crypto";
2761
- import { isLeaseProvider, NoopLeaseProvider } from "@mastra/core/events";
2762
- import { MastraWorker } from "@mastra/core/worker";
2763
- var API_PREFIX = "/v1/server/github-app";
2764
- var DEFAULT_POLL_INTERVAL_MS = 2e4;
2765
- var EVENT_PAGE_SIZE = 500;
2766
- var MIN_LEASE_TTL_MS = 3e4;
2767
- var CURSOR_ORG_ID = "__platform_github_event_worker__";
2768
- var CURSOR_USER_ID = "worker";
2769
- var SUPPORTED_EVENTS = /* @__PURE__ */ new Set([
2770
- "issues",
2771
- "issue_comment",
2772
- "pull_request",
2773
- "pull_request_review",
2774
- "pull_request_review_comment"
2775
- ]);
2776
- var AUTHOR_GATED_KINDS2 = /* @__PURE__ */ new Set([
2777
- "issue-comment",
2778
- "pull-request-comment",
2779
- "pull-request-review",
2780
- "pull-request-review-comment"
2781
- ]);
2782
- var AUTHORIZED_BOTS2 = /* @__PURE__ */ new Set(["coderabbitai[bot]", "devin-ai-integration[bot]"]);
2783
- var AUTHORIZED_PERMISSIONS2 = /* @__PURE__ */ new Set(["admin", "maintain", "write"]);
2784
- var PERMISSION_CHECK_TIMEOUT_MS2 = 5e3;
2785
- var PlatformGithubEventWorker = class extends MastraWorker {
2786
- name = "platform-github-events";
2787
- #client;
2788
- #controller;
2789
- #github;
2790
- #storage;
2791
- #ingestFactoryEvent;
2792
- #intervalMs;
2793
- #now;
2794
- #dispatch;
2795
- #leaseOwner = randomUUID2();
2796
- #running = false;
2797
- #timer;
2798
- #leaseRenewalTimer;
2799
- #inFlight;
2800
- #leaseProvider = NoopLeaseProvider;
2801
- #leaseTtlMs;
2802
- #hasLease = false;
2803
- #startedAt = 0;
2804
- #settings = { version: 1, repositories: {} };
2805
- constructor(config) {
2806
- super();
2807
- this.#client = config.client;
2808
- this.#controller = config.controller;
2809
- this.#github = config.github;
2810
- this.#storage = config.storage;
2811
- this.#ingestFactoryEvent = config.ingestFactoryEvent;
2812
- this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;
2813
- if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {
2814
- throw new Error("Platform GitHub event polling interval must be a positive number.");
2815
- }
2816
- this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);
2817
- this.#now = config.now ?? Date.now;
2818
- this.#dispatch = config.dispatch ?? dispatchGithubWebhook;
2819
- }
2820
- async init(deps) {
2821
- await super.init(deps);
2822
- this.#leaseProvider = getLeaseProvider(deps.pubsub);
2823
- }
2824
- async start() {
2825
- if (this.#running) return;
2826
- if (!this.deps) throw new Error("PlatformGithubEventWorker: call init() before start()");
2827
- this.#startedAt = this.#now() - 1;
2828
- this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));
2829
- this.#running = true;
2830
- this.deps.logger.info("Platform GitHub event polling started", {
2831
- intervalMs: this.#intervalMs,
2832
- leaseTtlMs: this.#leaseTtlMs
2833
- });
2834
- this.#schedule(0);
2835
- }
2836
- async stop() {
2837
- if (!this.#running) return;
2838
- this.#running = false;
2839
- if (this.#timer) clearTimeout(this.#timer);
2840
- this.#timer = void 0;
2841
- this.#stopLeaseRenewal();
2842
- await this.#inFlight;
2843
- if (this.#hasLease) {
2844
- await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => void 0);
2845
- this.#hasLease = false;
2846
- }
2847
- }
2848
- get isRunning() {
2849
- return this.#running;
2850
- }
2851
- #schedule(delayMs) {
2852
- if (!this.#running) return;
2853
- this.#timer = setTimeout(() => {
2854
- this.#timer = void 0;
2855
- const run = this.#tick();
2856
- this.#inFlight = run;
2857
- void run.finally(() => {
2858
- if (this.#inFlight === run) this.#inFlight = void 0;
2859
- });
2860
- }, delayMs);
2861
- this.#timer.unref?.();
2862
- }
2863
- async #tick() {
2864
- let nextDelay = this.#intervalMs;
2865
- try {
2866
- if (!await this.#ensureLease()) return;
2867
- nextDelay = await this.#poll();
2868
- } catch (error) {
2869
- nextDelay = retryDelay(error, this.#intervalMs);
2870
- this.deps?.logger.error("Platform GitHub event polling cycle failed", {
2871
- error: error instanceof Error ? error.message : String(error),
2872
- retryInMs: nextDelay
2873
- });
2874
- } finally {
2875
- this.#schedule(nextDelay);
2876
- }
2877
- }
2878
- async #ensureLease() {
2879
- if (this.#hasLease) return true;
2880
- const result = await this.#leaseProvider.acquireLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs);
2881
- this.#hasLease = result.acquired;
2882
- if (this.#hasLease) this.#startLeaseRenewal();
2883
- return this.#hasLease;
2884
- }
2885
- #startLeaseRenewal() {
2886
- if (this.#leaseRenewalTimer) return;
2887
- this.#leaseRenewalTimer = setInterval(
2888
- () => {
2889
- void this.#leaseProvider.renewLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs).then((renewed) => {
2890
- if (!renewed) {
2891
- this.#hasLease = false;
2892
- this.#stopLeaseRenewal();
2893
- }
2894
- }).catch((error) => {
2895
- this.#hasLease = false;
2896
- this.#stopLeaseRenewal();
2897
- this.deps?.logger.warn("Platform GitHub event polling lease renewal failed", {
2898
- error: error instanceof Error ? error.message : String(error)
2899
- });
2900
- });
2901
- },
2902
- Math.floor(this.#leaseTtlMs / 3)
2903
- );
2904
- this.#leaseRenewalTimer.unref?.();
2905
- }
2906
- #stopLeaseRenewal() {
2907
- if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);
2908
- this.#leaseRenewalTimer = void 0;
2909
- }
2910
- async #poll() {
2911
- const repositories = await this.#discoverRepositories();
2912
- let retryInMs = this.#intervalMs;
2913
- for (const repository of repositories) {
2914
- if (!this.#running || !this.#hasLease) break;
2915
- try {
2916
- await this.#pollRepository(repository.id);
2917
- } catch (error) {
2918
- const delay = retryDelay(error, this.#intervalMs);
2919
- retryInMs = Math.max(retryInMs, delay);
2920
- this.deps?.logger.error("Platform GitHub repository event polling failed", {
2921
- repositoryId: repository.id,
2922
- error: error instanceof Error ? error.message : String(error),
2923
- retryInMs: delay
2924
- });
2925
- if (error instanceof PlatformApiError && error.status === 429) break;
2926
- }
2927
- }
2928
- return retryInMs;
2929
- }
2930
- async #discoverRepositories() {
2931
- const result = await this.#client.request("GET", `${API_PREFIX}/installations`);
2932
- const repositories = /* @__PURE__ */ new Map();
2933
- for (const installation of result.installations) {
2934
- if (!installation.usable || installation.suspendedAt) continue;
2935
- const page = await this.#client.request(
2936
- "GET",
2937
- `${API_PREFIX}/installations/${installation.installationId}/repositories`
2938
- );
2939
- for (const repository of page.repositories) repositories.set(repository.id, repository);
2940
- }
2941
- return [...repositories.values()];
2942
- }
2943
- async #pollRepository(repositoryId) {
2944
- const key = String(repositoryId);
2945
- if (!this.#settings.repositories[key]) {
2946
- this.#settings.repositories[key] = { afterTimestamp: this.#startedAt };
2947
- await this.#saveSettings();
2948
- }
2949
- while (this.#running && this.#hasLease) {
2950
- const cursor = this.#settings.repositories[key];
2951
- const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE) });
2952
- if ("afterEventId" in cursor) query.set("afterEventId", cursor.afterEventId);
2953
- else query.set("afterTimestamp", String(cursor.afterTimestamp));
2954
- const pollStartedAt = performance.now();
2955
- const page = await this.#client.request(
2956
- "GET",
2957
- `${API_PREFIX}/repositories/${repositoryId}/events?${query}`
2958
- );
2959
- this.deps?.logger.info("Platform GitHub repository event poll completed", {
2960
- repositoryId,
2961
- eventCount: page.events.length,
2962
- latencyMs: Math.round(performance.now() - pollStartedAt)
2963
- });
2964
- if (page.events.length === 0 || !page.nextCursor) return;
2965
- for (const event of page.events) {
2966
- if (!this.#running || !this.#hasLease) return;
2967
- const parsed = parseEvent(event);
2968
- if (!parsed) {
2969
- this.deps?.logger.warn("Platform GitHub event log returned a malformed event", {
2970
- repositoryId,
2971
- eventId: event.id
2972
- });
2973
- continue;
2974
- }
2975
- if (isFactoryClosureEvent(parsed)) {
2976
- await this.#ingestFactoryEvent?.(parsed);
2977
- }
2978
- const result = await this.#dispatch(parsed, {
2979
- controller: this.#controller,
2980
- listSubscriptions: (target, options) => listPullRequestSubscriptionsForWebhook(target, options, this.#github.integrationStorage),
2981
- retireSubscription: (id, status) => retirePullRequestSubscription(id, status, this.#github.integrationStorage),
2982
- isAuthorizedSender: (notification) => this.#isAuthorizedSender(notification),
2983
- onTargetError: (subscription, error) => {
2984
- this.deps?.logger.error("Platform GitHub event delivery failed for a subscription", {
2985
- subscriptionId: subscription.id,
2986
- resourceId: subscription.resourceId,
2987
- threadId: subscription.threadId,
2988
- error: error instanceof Error ? error.message : String(error)
2989
- });
2990
- }
2991
- });
2992
- if (result.failed > 0) {
2993
- throw new Error(
2994
- `Platform GitHub event ${event.deliveryId} failed for ${result.failed} subscribed target(s).`
2995
- );
2996
- }
2997
- }
2998
- if (page.nextCursor === ("afterEventId" in cursor ? cursor.afterEventId : void 0)) return;
2999
- this.#settings.repositories[key] = { afterEventId: page.nextCursor };
3000
- await this.#saveSettings();
3001
- }
3002
- }
3003
- async #isAuthorizedSender(notification) {
3004
- if (!AUTHOR_GATED_KINDS2.has(notification.kind)) return true;
3005
- const sender = notification.metadata.sender;
3006
- const repository = notification.metadata.repository;
3007
- if (!sender || !repository) return false;
3008
- if (AUTHORIZED_BOTS2.has(sender)) return true;
3009
- const abortController = new AbortController();
3010
- const timeout = setTimeout(() => abortController.abort(), PERMISSION_CHECK_TIMEOUT_MS2);
3011
- try {
3012
- const permission = await this.#github.getRepositoryCollaboratorPermission(
3013
- notification.metadata.installationId,
3014
- repository,
3015
- sender,
3016
- abortController.signal
3017
- );
3018
- return permission !== void 0 && AUTHORIZED_PERMISSIONS2.has(permission);
3019
- } catch {
3020
- return false;
3021
- } finally {
3022
- clearTimeout(timeout);
3023
- }
3024
- }
3025
- async #saveSettings() {
3026
- await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);
3027
- }
3028
- #leaseKey() {
3029
- return `${this.name}:${this.#storage.integrationId}`;
3030
- }
3031
- };
3032
- function getLeaseProvider(pubsub) {
3033
- const getProvider = pubsub.getLeaseProvider;
3034
- if (typeof getProvider === "function") return getProvider.call(pubsub) ?? NoopLeaseProvider;
3035
- return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;
3036
- }
3037
- function normalizeSettings(value) {
3038
- if (!value || value.version !== 1 || !value.repositories || typeof value.repositories !== "object") {
3039
- return { version: 1, repositories: {} };
3040
- }
3041
- return { version: 1, repositories: { ...value.repositories } };
3042
- }
3043
- function isFactoryClosureEvent(event) {
3044
- return (event.event === "issues" || event.event === "pull_request") && event.payload.action === "closed";
3045
- }
3046
- function parseEvent(event) {
3047
- if (!event.id || !event.deliveryId || !SUPPORTED_EVENTS.has(event.event) || !event.payload || typeof event.payload !== "object" || Array.isArray(event.payload)) {
3048
- return null;
3049
- }
3050
- return {
3051
- event: event.event,
3052
- deliveryId: event.deliveryId,
3053
- payload: event.payload
3054
- };
3055
- }
3056
- function retryDelay(error, fallbackMs) {
3057
- if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {
3058
- return Math.max(fallbackMs, error.retryAfterSeconds * 1e3);
3059
- }
3060
- return fallbackMs;
3061
- }
3062
-
3063
- // src/integrations/platform/github/integration.ts
3064
- var PAGE_SIZE = 30;
3065
- var API_PREFIX2 = "/v1/server";
3066
- var INSTALLATION_REPOS_CACHE_TTL_MS = 3e4;
3067
- var REPOSITORY_ACCESS_CACHE_TTL_MS = 5 * 6e4;
3068
- var MAX_CACHE_ENTRIES = 1e3;
7
+ //#region src/integrations/platform/github/integration.ts
8
+ const PAGE_SIZE = 30;
9
+ const API_PREFIX = "/v1/server";
10
+ /**
11
+ * How long an installation's repository listing may be reused. The repos
12
+ * route and token minting both call it — often several times within one UI
13
+ * interaction — and each call is a full Platform round trip.
14
+ */
15
+ const INSTALLATION_REPOS_CACHE_TTL_MS = 3e4;
16
+ /**
17
+ * How long a minted repository-scoped token may be reused. GitHub
18
+ * installation tokens live ~60 minutes; 5 minutes keeps a wide validity
19
+ * margin while collapsing the per-session-materialization mint round trip.
20
+ */
21
+ const REPOSITORY_ACCESS_CACHE_TTL_MS = 5 * 6e4;
22
+ /**
23
+ * Upper bound for both TTL caches. Entries expire lazily on re-access, so
24
+ * without a hard cap keys that stop being queried would accumulate for the
25
+ * integration's (long) lifetime. Insertion-order eviction — matches the
26
+ * bounded verification cache in `@mastra/auth-studio`.
27
+ */
28
+ const MAX_CACHE_ENTRIES = 1e3;
3069
29
  function setBounded(cache, key, value) {
3070
- cache.delete(key);
3071
- cache.set(key, value);
3072
- if (cache.size > MAX_CACHE_ENTRIES) {
3073
- const oldest = cache.keys().next().value;
3074
- if (oldest !== void 0) cache.delete(oldest);
3075
- }
3076
- }
3077
- var REPOSITORY_TOKEN_PERMISSIONS = {
3078
- contents: "write",
3079
- issues: "write",
3080
- pull_requests: "write"
30
+ cache.delete(key);
31
+ cache.set(key, value);
32
+ if (cache.size > MAX_CACHE_ENTRIES) {
33
+ const oldest = cache.keys().next().value;
34
+ if (oldest !== void 0) cache.delete(oldest);
35
+ }
36
+ }
37
+ const REPOSITORY_TOKEN_PERMISSIONS = {
38
+ contents: "write",
39
+ issues: "write",
40
+ pull_requests: "write"
3081
41
  };
3082
- function loose2(c) {
3083
- return c;
42
+ function loose(c) {
43
+ return c;
3084
44
  }
3085
45
  function routeBaseUrl(ctx, requestUrl) {
3086
- return (ctx.baseUrl || new URL(requestUrl).origin).replace(/\/+$/, "");
46
+ return (ctx.baseUrl || new URL(requestUrl).origin).replace(/\/+$/, "");
3087
47
  }
3088
48
  var PlatformGithubIntegration = class {
3089
- id = "github";
3090
- #client;
3091
- #endpointHost;
3092
- #pollingEnabled;
3093
- #pollingIntervalMs;
3094
- #storage;
3095
- #integrationStorage;
3096
- /** installationId → cached repository listing (TTL-bounded). */
3097
- #installationReposCache = /* @__PURE__ */ new Map();
3098
- /** `orgId:repositoryId` → cached repository access (TTL-bounded). */
3099
- #repositoryAccessCache = /* @__PURE__ */ new Map();
3100
- intake = {
3101
- resolveIntakeDispatch: (input) => this.#resolveIntakeDispatch(input),
3102
- listSources: async ({ orgId, userId }) => {
3103
- const installations = await this.#client.request("GET", `${API_PREFIX2}/github-app/installations`);
3104
- const usable = installations.installations.filter(
3105
- (installation) => installation.usable && !installation.suspendedAt
3106
- );
3107
- const repositories = await Promise.all(
3108
- usable.map(async (installation) => {
3109
- const storedInstallation = await this.versionControl.registerInstallation({
3110
- orgId,
3111
- userId,
3112
- installation: {
3113
- externalId: String(installation.installationId),
3114
- accountName: installation.accountLogin,
3115
- accountType: installation.accountType
3116
- }
3117
- });
3118
- const result = await this.#client.request("GET", `${API_PREFIX2}/github-app/installations/${installation.installationId}/repositories`);
3119
- await this.versionControl.registerRepositories({
3120
- orgId,
3121
- installationId: storedInstallation.id,
3122
- repositories: result.repositories.map((repository) => ({
3123
- externalId: String(repository.id),
3124
- slug: repository.fullName,
3125
- defaultBranch: repository.defaultBranch,
3126
- metadata: { private: repository.private, url: repository.htmlUrl }
3127
- }))
3128
- });
3129
- return result.repositories.map((repository) => ({ repository, installation }));
3130
- })
3131
- );
3132
- return repositories.flat().map(({ repository, installation }) => ({
3133
- id: repository.fullName,
3134
- name: repository.fullName,
3135
- type: "repository",
3136
- metadata: {
3137
- installationId: installation.installationId,
3138
- accountLogin: installation.accountLogin,
3139
- accountType: installation.accountType,
3140
- repositoryId: repository.id,
3141
- defaultBranch: repository.defaultBranch,
3142
- private: repository.private,
3143
- url: repository.htmlUrl
3144
- }
3145
- }));
3146
- },
3147
- listItems: async ({ sourceIds, cursor }) => {
3148
- const page = parsePositiveCursor(cursor);
3149
- const pages = await Promise.all(
3150
- sourceIds.map(async (sourceId) => {
3151
- const connection = { type: "app-installation", installationId: 1 };
3152
- const [issues, pullRequests] = await Promise.all([
3153
- this.#listIssues(connection, sourceId, page),
3154
- this.#listPullRequests({ connection, sourceId, includeDrafts: false, cursor: String(page) })
3155
- ]);
3156
- return {
3157
- items: [
3158
- ...issues.issues.map((issue) => ({
3159
- source: { type: "issue", externalId: `${sourceId}:${issue.id}`, url: issue.url },
3160
- sourceId,
3161
- title: issue.title,
3162
- status: issue.state ?? void 0,
3163
- labels: issue.labels,
3164
- assignee: issue.assignee,
3165
- createdAt: issue.createdAt,
3166
- updatedAt: issue.updatedAt,
3167
- metadata: { repository: sourceId, number: Number(issue.id), author: issue.author }
3168
- })),
3169
- ...pullRequests.pullRequests.map((pullRequest) => ({
3170
- source: { type: "pull-request", externalId: `${sourceId}:${pullRequest.id}`, url: pullRequest.url },
3171
- sourceId,
3172
- title: pullRequest.title,
3173
- status: pullRequest.state,
3174
- createdAt: pullRequest.createdAt,
3175
- updatedAt: pullRequest.updatedAt,
3176
- metadata: {
3177
- repository: sourceId,
3178
- number: Number(pullRequest.id),
3179
- author: pullRequest.author,
3180
- baseBranch: pullRequest.baseBranch,
3181
- headBranch: pullRequest.headBranch
3182
- }
3183
- }))
3184
- ],
3185
- hasNextPage: issues.nextCursor !== null || pullRequests.nextCursor !== null
3186
- };
3187
- })
3188
- );
3189
- return {
3190
- items: pages.flatMap((result) => result.items),
3191
- nextCursor: pages.some((result) => result.hasNextPage) ? String(page + 1) : null
3192
- };
3193
- },
3194
- listIssues: async (input) => {
3195
- requireGithubConnection(input.connection);
3196
- const sourceId = requireSingleSource(input.sourceIds, "GitHub Intake requires exactly one repository source.");
3197
- return this.#listIssues(input.connection, sourceId, parsePositiveCursor(input.cursor), input.labels);
3198
- },
3199
- getIssue: (input) => this.#getIssue(input.connection, input.sourceId, input.issueId),
3200
- createComment: (input) => this.#createIssueComment(input),
3201
- updateIssue: (input) => this.#updateIntakeIssue(input)
3202
- };
3203
- versionControl = {
3204
- initialize: ({ storage }) => {
3205
- this.#storage = storage;
3206
- },
3207
- registerInstallation: ({ orgId, userId, installation }) => this.storage.installations.upsert({
3208
- orgId,
3209
- connectedByUserId: userId,
3210
- externalId: installation.externalId,
3211
- accountName: installation.accountName,
3212
- accountType: installation.accountType,
3213
- providerMetadata: installation.metadata
3214
- }),
3215
- registerRepositories: ({ orgId, installationId, repositories }) => Promise.all(
3216
- repositories.map(
3217
- (repository) => this.storage.repositories.upsert({
3218
- orgId,
3219
- input: {
3220
- installationId,
3221
- externalId: repository.externalId,
3222
- slug: repository.slug,
3223
- defaultBranch: repository.defaultBranch,
3224
- providerMetadata: repository.metadata
3225
- }
3226
- })
3227
- )
3228
- ),
3229
- getRepositoryAccess: async ({ orgId, repositoryId }) => {
3230
- const cacheKey = `${orgId}:${repositoryId}`;
3231
- const cached = this.#repositoryAccessCache.get(cacheKey);
3232
- if (cached && cached.expiresAt > Date.now()) return cached.access;
3233
- this.#repositoryAccessCache.delete(cacheKey);
3234
- const repository = await this.storage.repositories.get({ orgId, id: repositoryId });
3235
- if (!repository) throw new Error("Version-control repository not found.");
3236
- const cloneUrl = `https://github.com/${repository.slug}.git`;
3237
- const installation = await this.storage.installations.get({ orgId, id: repository.installationId });
3238
- if (!installation) throw new Error("Version-control installation not found.");
3239
- const installationId = parsePositiveInteger(installation.externalId);
3240
- if (installationId === null) throw new Error("GitHub installation id is invalid.");
3241
- const repositoryName = splitRepository(repository.slug).repo;
3242
- const token = await this.#client.request(
3243
- "POST",
3244
- `${API_PREFIX2}/github-app/installations/${installationId}/token`,
3245
- { repositories: [repositoryName], permissions: REPOSITORY_TOKEN_PERMISSIONS }
3246
- );
3247
- const access = {
3248
- cloneUrl,
3249
- authorization: { scheme: "bearer", token: token.token }
3250
- };
3251
- setBounded(this.#repositoryAccessCache, cacheKey, {
3252
- access,
3253
- expiresAt: Date.now() + REPOSITORY_ACCESS_CACHE_TTL_MS
3254
- });
3255
- return access;
3256
- },
3257
- listPullRequests: (input) => this.#listPullRequests(input),
3258
- getPullRequest: (input) => this.#getPullRequest(input),
3259
- createPullRequest: (input) => this.#createPullRequest(input),
3260
- updatePullRequest: (input) => this.#updatePullRequest(input),
3261
- closePullRequest: (input) => this.#updatePullRequest({ ...input, state: "closed" }),
3262
- mergePullRequest: (input) => this.#mergePullRequest(input),
3263
- listComments: (input) => this.#listComments(input),
3264
- createComment: (input) => this.#createComment(input),
3265
- updateComment: (input) => this.#updateComment(input),
3266
- deleteComment: (input) => this.#deleteComment(input),
3267
- listReviews: (input) => this.#listReviews(input),
3268
- getReview: (input) => this.#getReview(input),
3269
- createReview: (input) => this.#createReview(input),
3270
- updateReview: (input) => this.#updateReview(input),
3271
- submitReview: (input) => this.#submitReview(input),
3272
- dismissReview: (input) => this.#dismissReview(input),
3273
- deletePendingReview: (input) => this.#deletePendingReview(input),
3274
- listReviewComments: (input) => this.#listReviewComments(input),
3275
- createReviewComment: (input) => this.#createReviewComment(input),
3276
- updateReviewComment: (input) => this.#updateReviewComment(input),
3277
- deleteReviewComment: (input) => this.#deleteReviewComment(input),
3278
- listRequestedReviewers: (input) => this.#requestedReviewers("GET", input),
3279
- requestReviewers: (input) => this.#requestedReviewers("POST", input),
3280
- removeRequestedReviewers: (input) => this.#requestedReviewers("DELETE", input)
3281
- };
3282
- constructor() {
3283
- const config = platformApiClientConfigFromEnv();
3284
- this.#client = new PlatformApiClient(config);
3285
- this.#endpointHost = new URL(config.baseUrl).host;
3286
- this.#pollingEnabled = process.env.MASTRA_PLATFORM_GITHUB_POLLING_ENABLED?.trim().toLowerCase() !== "false";
3287
- this.#pollingIntervalMs = optionalPositiveIntegerEnv("MASTRA_PLATFORM_GITHUB_POLLING_INTERVAL_MS");
3288
- }
3289
- get storage() {
3290
- if (!this.#storage) throw new Error("PlatformGithubIntegration source-control storage has not been initialized.");
3291
- return this.#storage;
3292
- }
3293
- get sourceControlStorage() {
3294
- return this.storage;
3295
- }
3296
- get integrationStorage() {
3297
- if (!this.#integrationStorage) {
3298
- throw new Error("PlatformGithubIntegration generic storage has not been initialized.");
3299
- }
3300
- return this.#integrationStorage;
3301
- }
3302
- /** Resolve a stored GitHub locator without scanning installations or repositories. */
3303
- async #resolveIntakeDispatch({
3304
- orgId,
3305
- externalSource
3306
- }) {
3307
- const target = parseGithubExternalTarget(externalSource.externalId);
3308
- if (!target) return null;
3309
- const repository = target.repository.includes("/") ? target.repository : (await this.storage.repositories.findByExternalId({ orgId, externalId: target.repository }))?.slug;
3310
- if (!repository) return null;
3311
- return {
3312
- connection: { type: "app-installation", installationId: 1 },
3313
- sourceId: repository,
3314
- issueId: target.issueId
3315
- };
3316
- }
3317
- initialize({ storage }) {
3318
- this.#integrationStorage = storage;
3319
- logPlatformInfo("Platform GitHub integration initialized", {
3320
- endpointHost: this.#endpointHost,
3321
- pollingEnabled: this.#pollingEnabled,
3322
- pollingIntervalMs: this.#pollingIntervalMs
3323
- });
3324
- }
3325
- routes(ctx) {
3326
- const ingestFactoryEvent = attachGithubRules(this, ctx);
3327
- return [
3328
- this.#statusRoute(ctx),
3329
- this.#connectRoute(ctx),
3330
- this.#connectUserRoute(ctx),
3331
- ...buildGithubRoutes({
3332
- auth: ctx.auth,
3333
- fleet: ctx.fleet,
3334
- storage: ctx.factoryStorage,
3335
- github: this,
3336
- stateSigner: ctx.stateSigner,
3337
- baseUrl: ctx.baseUrl,
3338
- controller: ctx.controller,
3339
- projects: ctx.storage.projects,
3340
- emitAudit: ctx.hooks?.emitAudit,
3341
- ingestFactoryEvent
3342
- }).filter(
3343
- (route) => route.path !== "/web/github/status" && route.path !== "/web/github/webhook" && !route.path.startsWith("/auth/github/")
3344
- )
3345
- ];
3346
- }
3347
- #statusRoute(ctx) {
3348
- return registerApiRoute2("/web/github/status", {
3349
- method: "GET",
3350
- requiresAuth: false,
3351
- handler: async (c) => {
3352
- await ctx.auth.ensureUser(loose2(c));
3353
- const tenant = ctx.auth.tenant(loose2(c));
3354
- if (!tenant) return c.json({ error: "unauthorized", reason: "auth_required" }, 401);
3355
- if (!tenant.orgId) {
3356
- return c.json({
3357
- enabled: true,
3358
- sandboxEnabled: ctx.fleet.enabled,
3359
- organizationRequired: true,
3360
- connected: false,
3361
- installations: [],
3362
- userConnected: false,
3363
- userGithubUsername: null,
3364
- reason: "organization_required",
3365
- diagnostics: this.diagnostics()
3366
- });
3367
- }
3368
- const [installations, userConnection] = await Promise.all([
3369
- this.#syncInstallations(tenant.orgId, tenant.userId),
3370
- this.#fetchUserConnection(tenant.userId)
3371
- ]);
3372
- return c.json({
3373
- enabled: true,
3374
- sandboxEnabled: ctx.fleet.enabled,
3375
- connected: installations.length > 0,
3376
- installations: installations.map((installation) => ({
3377
- installationId: Number(installation.externalId),
3378
- accountLogin: installation.accountName,
3379
- accountType: installation.accountType
3380
- })),
3381
- userConnected: userConnection.connected,
3382
- userGithubUsername: userConnection.githubUsername,
3383
- reason: installations.length > 0 ? "ready" : "not_connected",
3384
- diagnostics: this.diagnostics()
3385
- });
3386
- }
3387
- });
3388
- }
3389
- #connectRoute(ctx) {
3390
- return registerApiRoute2("/auth/github/connect", {
3391
- method: "GET",
3392
- requiresAuth: false,
3393
- handler: async (c) => {
3394
- await ctx.auth.ensureUser(loose2(c));
3395
- const tenant = ctx.auth.tenant(loose2(c));
3396
- if (!tenant?.orgId) return c.json({ error: "unauthorized" }, 401);
3397
- const redirectTo = c.req.query("redirectTo") || c.req.query("return_to") || "/";
3398
- const originator = routeBaseUrl(ctx, c.req.url);
3399
- logPlatformInfo("Starting Platform GitHub connect flow", {
3400
- orgId: tenant.orgId,
3401
- redirectTo,
3402
- originator
3403
- });
3404
- const query = new URLSearchParams({
3405
- action: "install",
3406
- redirectTo,
3407
- originator
3408
- });
3409
- const { url } = await this.#client.request(
3410
- "GET",
3411
- `${API_PREFIX2}/github-app/install-url?${query}`
3412
- );
3413
- return c.redirect(url);
3414
- }
3415
- });
3416
- }
3417
- #connectUserRoute(ctx) {
3418
- return registerApiRoute2("/auth/github/connect-user", {
3419
- method: "GET",
3420
- requiresAuth: false,
3421
- handler: async (c) => {
3422
- await ctx.auth.ensureUser(loose2(c));
3423
- const tenant = ctx.auth.tenant(loose2(c));
3424
- if (!tenant?.orgId) return c.json({ error: "unauthorized" }, 401);
3425
- const redirectTo = c.req.query("redirectTo") || c.req.query("return_to") || "/";
3426
- const originator = routeBaseUrl(ctx, c.req.url);
3427
- logPlatformInfo("Starting Platform GitHub user authorization flow", {
3428
- orgId: tenant.orgId,
3429
- redirectTo,
3430
- originator
3431
- });
3432
- const query = new URLSearchParams({
3433
- userId: tenant.userId,
3434
- redirectTo,
3435
- originator
3436
- });
3437
- const { url } = await this.#client.request(
3438
- "GET",
3439
- `${API_PREFIX2}/github-app/authenticate?${query}`
3440
- );
3441
- return c.redirect(url);
3442
- }
3443
- });
3444
- }
3445
- /**
3446
- * Personal GitHub connection status for the acting user. Returns
3447
- * not-connected when the platform predates the user-connection endpoint.
3448
- */
3449
- async #fetchUserConnection(userId) {
3450
- try {
3451
- const connection = await this.#client.request(
3452
- "GET",
3453
- `${API_PREFIX2}/github-app/user-connection?${new URLSearchParams({ userId })}`
3454
- );
3455
- if (!connection.connected && connection.reason) {
3456
- logPlatformWarn("Platform GitHub user connection verification failed", {
3457
- userId,
3458
- reason: connection.reason
3459
- });
3460
- }
3461
- return connection;
3462
- } catch {
3463
- return { connected: false, githubUsername: null };
3464
- }
3465
- }
3466
- async #syncInstallations(orgId, userId) {
3467
- const result = await this.#client.request(
3468
- "GET",
3469
- `${API_PREFIX2}/github-app/installations`
3470
- );
3471
- const usableInstallations = result.installations.filter(
3472
- (installation) => installation.usable && !installation.suspendedAt
3473
- );
3474
- return Promise.all(
3475
- usableInstallations.map(
3476
- (installation) => this.versionControl.registerInstallation({
3477
- orgId,
3478
- userId,
3479
- installation: {
3480
- externalId: String(installation.installationId),
3481
- accountName: installation.accountLogin,
3482
- accountType: installation.accountType
3483
- }
3484
- })
3485
- )
3486
- );
3487
- }
3488
- workers(ctx) {
3489
- if (!this.#pollingEnabled) return [];
3490
- if (!ctx.controller) {
3491
- throw new Error("Platform GitHub event polling requires the mounted Mastra Code controller.");
3492
- }
3493
- return [
3494
- new PlatformGithubEventWorker({
3495
- client: this.#client,
3496
- controller: ctx.controller,
3497
- github: this,
3498
- storage: ctx.storage.generic,
3499
- ingestFactoryEvent: attachGithubRules(this, ctx),
3500
- intervalMs: this.#pollingIntervalMs
3501
- })
3502
- ];
3503
- }
3504
- sessionTools({ requestContext }) {
3505
- return createGithubSubscriptionTools(requestContext, this);
3506
- }
3507
- async postToolObserver({
3508
- toolContext,
3509
- requestContext
3510
- }) {
3511
- const pullRequestUrl = parseCreatedPullRequest(toolContext);
3512
- if (!pullRequestUrl || !requestContext) return;
3513
- await subscribeCurrentSessionToPullRequest(
3514
- requestContext,
3515
- pullRequestUrl,
3516
- "auto-gh-pr-create",
3517
- this
3518
- );
3519
- }
3520
- diagnostics() {
3521
- return {
3522
- mode: "platform",
3523
- endpointHost: this.#endpointHost,
3524
- polling: {
3525
- enabled: this.#pollingEnabled,
3526
- ...this.#pollingIntervalMs === void 0 ? {} : { intervalMs: this.#pollingIntervalMs }
3527
- }
3528
- };
3529
- }
3530
- async getRepositoryCollaboratorPermission(_installationId, repoFullName, username, signal) {
3531
- let repository;
3532
- try {
3533
- repository = splitRepository(repoFullName);
3534
- } catch {
3535
- return void 0;
3536
- }
3537
- try {
3538
- const result = await this.#client.request(
3539
- "GET",
3540
- `${API_PREFIX2}/github/repos/${encodeURIComponent(repository.owner)}/${encodeURIComponent(repository.repo)}/collaborators/${encodeURIComponent(username)}/permission`,
3541
- void 0,
3542
- { signal }
3543
- );
3544
- return result.permission;
3545
- } catch {
3546
- return void 0;
3547
- }
3548
- }
3549
- async listInstallationRepos(installationId) {
3550
- const cached = this.#installationReposCache.get(installationId);
3551
- if (cached && cached.expiresAt > Date.now()) return cached.repos;
3552
- this.#installationReposCache.delete(installationId);
3553
- const result = await this.#client.request("GET", `${API_PREFIX2}/github-app/installations/${installationId}/repositories`);
3554
- const repos = result.repositories.map((repository) => ({ ...repository, installationId }));
3555
- setBounded(this.#installationReposCache, installationId, {
3556
- repos,
3557
- expiresAt: Date.now() + INSTALLATION_REPOS_CACHE_TTL_MS
3558
- });
3559
- return repos;
3560
- }
3561
- async mintInstallationToken(installationId) {
3562
- const repositories = await this.listInstallationRepos(installationId);
3563
- if (repositories.length === 0 || repositories.length > 10) {
3564
- throw new Error("Platform GitHub token minting requires between one and ten installation repositories.");
3565
- }
3566
- const result = await this.#client.request(
3567
- "POST",
3568
- `${API_PREFIX2}/github-app/installations/${installationId}/token`,
3569
- { repositories: repositories.map((repository) => repository.name), permissions: REPOSITORY_TOKEN_PERMISSIONS }
3570
- );
3571
- return result.token;
3572
- }
3573
- async addIssueLabels(_installationId, sourceId, issueNumber, labels) {
3574
- const result = await this.#client.request(
3575
- "POST",
3576
- repositoryPath(sourceId, `issues/${issueNumber}/labels`),
3577
- { labels }
3578
- );
3579
- return result.labels;
3580
- }
3581
- getInstallationOctokit(_installationId) {
3582
- return {
3583
- pulls: {
3584
- get: async ({ owner, repo, pull_number }) => {
3585
- const data = await this.#client.request(
3586
- "GET",
3587
- repositoryPath(`${owner}/${repo}`, `pulls/${pull_number}`)
3588
- );
3589
- return { data: { base: { repo: { id: data.base.repo.id } } } };
3590
- }
3591
- }
3592
- };
3593
- }
3594
- async #listIssues(connection, sourceId, page, labels) {
3595
- requireGithubConnection(connection);
3596
- const path2 = repositoryPath(sourceId, "issues");
3597
- const query = new URLSearchParams({ state: "open", page: String(page), per_page: String(PAGE_SIZE) });
3598
- const normalizedLabels = normalizeLabels(labels);
3599
- if (normalizedLabels.length > 0) query.set("label", normalizedLabels.join(","));
3600
- const result = await this.#client.request("GET", `${path2}?${query}`);
3601
- return {
3602
- issues: result.issues.map((issue) => parseIntakeIssue(sourceId, issue)),
3603
- nextCursor: result.issues.length === PAGE_SIZE ? String(page + 1) : null
3604
- };
3605
- }
3606
- async #getIssue(connection, sourceId, issueId) {
3607
- requireGithubConnection(connection);
3608
- const repository = requireSource(sourceId, "GitHub Intake requires a repository source.");
3609
- const issueNumber = requirePositiveId(issueId, "issue");
3610
- try {
3611
- const [issue, comments] = await Promise.all([
3612
- this.#client.request("GET", repositoryPath(repository, `issues/${issueNumber}`)),
3613
- this.#client.request(
3614
- "GET",
3615
- `${repositoryPath(repository, `issues/${issueNumber}/comments`)}?per_page=100`
3616
- )
3617
- ]);
3618
- return parseIntakeIssueDetail(repository, issue, comments.comments);
3619
- } catch (error) {
3620
- if (isNotFound(error)) return null;
3621
- throw error;
3622
- }
3623
- }
3624
- async #updateIntakeIssue(input) {
3625
- requireGithubConnection(input.connection);
3626
- const repository = requireSource(input.sourceId, "GitHub Intake requires a repository source.");
3627
- const issueNumber = requirePositiveId(input.issueId, "issue");
3628
- if (input.state.kind === "byName") {
3629
- logPlatformWarn(`Platform GitHub: updateIssue byName is not supported (name=${input.state.name}); ignoring.`);
3630
- return null;
3631
- }
3632
- const targetState = input.state.stateType === "unstarted" || input.state.stateType === "started" ? "open" : "closed";
3633
- const stateReason = targetState === "closed" ? input.state.stateType === "canceled" ? "not_planned" : "completed" : null;
3634
- try {
3635
- await this.#client.request("GET", repositoryPath(repository, `pulls/${issueNumber}`));
3636
- logPlatformWarn(`Platform GitHub: updateIssue rejected \u2014 target ${repository}#${issueNumber} is a pull request.`);
3637
- return null;
3638
- } catch (error) {
3639
- if (!isNotFound(error)) throw error;
3640
- }
3641
- try {
3642
- const issue = await this.#client.request(
3643
- "PATCH",
3644
- repositoryPath(repository, `issues/${issueNumber}`),
3645
- {
3646
- state: targetState,
3647
- ...stateReason ? { state_reason: stateReason } : {}
3648
- },
3649
- { actingUserId: input.actingUserId }
3650
- );
3651
- return parseIntakeIssue(repository, issue);
3652
- } catch (error) {
3653
- if (isNotFound(error)) return null;
3654
- throw error;
3655
- }
3656
- }
3657
- async #createIssueComment(input) {
3658
- requireGithubConnection(input.connection);
3659
- const repository = requireSource(input.sourceId, "GitHub Intake requires a repository source.");
3660
- const issueNumber = requirePositiveId(input.issueId, "issue");
3661
- try {
3662
- const comment = await this.#client.request(
3663
- "POST",
3664
- repositoryPath(repository, `issues/${issueNumber}/comments`),
3665
- { body: input.body },
3666
- { actingUserId: input.actingUserId }
3667
- );
3668
- return { id: String(comment.id), url: comment.htmlUrl };
3669
- } catch (error) {
3670
- if (isNotFound(error)) return null;
3671
- throw error;
3672
- }
3673
- }
3674
- async #listPullRequests(input) {
3675
- requireGithubConnection(input.connection);
3676
- const page = parsePositiveCursor(input.cursor);
3677
- const query = new URLSearchParams({
3678
- state: input.state ?? "open",
3679
- page: String(page),
3680
- per_page: String(PAGE_SIZE)
3681
- });
3682
- const result = await this.#client.request(
3683
- "GET",
3684
- `${repositoryPath(input.sourceId, "pulls")}?${query}`
3685
- );
3686
- return {
3687
- pullRequests: result.pullRequests.filter((pullRequest) => input.includeDrafts !== false || !pullRequest.draft).map(parsePullRequest2),
3688
- nextCursor: result.pullRequests.length === PAGE_SIZE ? String(page + 1) : null
3689
- };
3690
- }
3691
- async #getPullRequest(input) {
3692
- try {
3693
- return parsePullRequest2(
3694
- await this.#client.request("GET", pullRequestPath(input, input.pullRequestId))
3695
- );
3696
- } catch (error) {
3697
- if (isNotFound(error)) return null;
3698
- throw error;
3699
- }
3700
- }
3701
- async #createPullRequest(input) {
3702
- requireGithubConnection(input.connection);
3703
- const result = await this.#client.request(
3704
- "POST",
3705
- repositoryPath(input.sourceId, "pulls"),
3706
- {
3707
- head: input.headBranch,
3708
- base: input.baseBranch,
3709
- title: input.title,
3710
- body: input.body,
3711
- draft: input.draft
3712
- },
3713
- { actingUserId: input.actingUserId }
3714
- );
3715
- return parsePullRequest2(result);
3716
- }
3717
- async #updatePullRequest(input) {
3718
- const result = await this.#client.request(
3719
- "PATCH",
3720
- pullRequestPath(input, input.pullRequestId),
3721
- {
3722
- title: input.title,
3723
- body: input.body === null ? "" : input.body,
3724
- base: input.baseBranch,
3725
- state: input.state
3726
- },
3727
- { actingUserId: input.actingUserId }
3728
- );
3729
- return parsePullRequest2(result);
3730
- }
3731
- #mergePullRequest(input) {
3732
- return this.#client.request(
3733
- "PUT",
3734
- `${pullRequestPath(input, input.pullRequestId)}/merge`,
3735
- { commitTitle: input.commitTitle, commitMessage: input.commitMessage, method: input.method },
3736
- { actingUserId: input.actingUserId }
3737
- );
3738
- }
3739
- async #listComments(input) {
3740
- const page = parsePositiveCursor(input.cursor);
3741
- const result = await this.#client.request(
3742
- "GET",
3743
- `${repositoryPath(input.sourceId, `issues/${requirePositiveId(input.pullRequestId, "pull request")}/comments`)}?page=${page}&per_page=${PAGE_SIZE}`
3744
- );
3745
- return {
3746
- comments: result.comments.map(parseComment),
3747
- nextCursor: result.comments.length === PAGE_SIZE ? String(page + 1) : null
3748
- };
3749
- }
3750
- async #createComment(input) {
3751
- const comment = await this.#client.request(
3752
- "POST",
3753
- repositoryPath(input.sourceId, `issues/${requirePositiveId(input.pullRequestId, "pull request")}/comments`),
3754
- { body: input.body },
3755
- { actingUserId: input.actingUserId }
3756
- );
3757
- return parseComment(comment);
3758
- }
3759
- async #updateComment(input) {
3760
- requireGithubConnection(input.connection);
3761
- const comment = await this.#client.request(
3762
- "PATCH",
3763
- repositoryPath(input.sourceId, `issues/comments/${requirePositiveId(input.commentId, "comment")}`),
3764
- { body: input.body },
3765
- { actingUserId: input.actingUserId }
3766
- );
3767
- return parseComment(comment);
3768
- }
3769
- async #deleteComment(input) {
3770
- requireGithubConnection(input.connection);
3771
- await this.#client.request(
3772
- "DELETE",
3773
- repositoryPath(input.sourceId, `issues/comments/${requirePositiveId(input.commentId, "comment")}`),
3774
- void 0,
3775
- { actingUserId: input.actingUserId }
3776
- );
3777
- }
3778
- async #listReviews(input) {
3779
- const page = parsePositiveCursor(input.cursor);
3780
- const result = await this.#client.request(
3781
- "GET",
3782
- `${pullRequestPath(input, input.pullRequestId)}/reviews?page=${page}&per_page=${PAGE_SIZE}`
3783
- );
3784
- return {
3785
- reviews: result.reviews.map(parseReview),
3786
- nextCursor: result.reviews.length === PAGE_SIZE ? String(page + 1) : null
3787
- };
3788
- }
3789
- async #getReview(input) {
3790
- try {
3791
- return parseReview(
3792
- await this.#client.request(
3793
- "GET",
3794
- `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}`
3795
- )
3796
- );
3797
- } catch (error) {
3798
- if (isNotFound(error)) return null;
3799
- throw error;
3800
- }
3801
- }
3802
- async #createReview(input) {
3803
- const review = await this.#client.request(
3804
- "POST",
3805
- `${pullRequestPath(input, input.pullRequestId)}/reviews`,
3806
- { body: input.body, commitId: input.commitId, event: input.event ? reviewEvent(input.event) : void 0 },
3807
- { actingUserId: input.actingUserId }
3808
- );
3809
- return parseReview(review);
3810
- }
3811
- async #updateReview(input) {
3812
- const review = await this.#client.request(
3813
- "PUT",
3814
- `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}`,
3815
- { body: input.body },
3816
- { actingUserId: input.actingUserId }
3817
- );
3818
- return parseReview(review);
3819
- }
3820
- async #submitReview(input) {
3821
- const review = await this.#client.request(
3822
- "POST",
3823
- `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}/events`,
3824
- { body: input.body, event: reviewEvent(input.event) },
3825
- { actingUserId: input.actingUserId }
3826
- );
3827
- return parseReview(review);
3828
- }
3829
- async #dismissReview(input) {
3830
- const review = await this.#client.request(
3831
- "PUT",
3832
- `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}/dismissals`,
3833
- { message: input.message },
3834
- { actingUserId: input.actingUserId }
3835
- );
3836
- return parseReview(review);
3837
- }
3838
- async #deletePendingReview(input) {
3839
- await this.#client.request(
3840
- "DELETE",
3841
- `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}`,
3842
- void 0,
3843
- { actingUserId: input.actingUserId }
3844
- );
3845
- }
3846
- async #listReviewComments(input) {
3847
- const page = parsePositiveCursor(input.cursor);
3848
- const result = await this.#client.request(
3849
- "GET",
3850
- `${pullRequestPath(input, input.pullRequestId)}/comments?page=${page}&per_page=${PAGE_SIZE}`
3851
- );
3852
- return {
3853
- comments: result.comments.map(parseReviewComment),
3854
- nextCursor: result.comments.length === PAGE_SIZE ? String(page + 1) : null
3855
- };
3856
- }
3857
- async #createReviewComment(input) {
3858
- let body;
3859
- if (input.replyToId !== void 0) {
3860
- body = { body: input.body, replyToId: requirePositiveId(input.replyToId, "review comment") };
3861
- } else {
3862
- if (!input.commitId || !input.path || input.line === void 0 || !input.side) {
3863
- throw new Error("A review comment requires commitId, path, line, and side unless it is a reply.");
3864
- }
3865
- body = {
3866
- body: input.body,
3867
- commitId: input.commitId,
3868
- path: input.path,
3869
- line: input.line,
3870
- side: input.side.toUpperCase(),
3871
- startLine: input.startLine,
3872
- startSide: input.startSide?.toUpperCase()
3873
- };
3874
- }
3875
- return parseReviewComment(
3876
- await this.#client.request(
3877
- "POST",
3878
- `${pullRequestPath(input, input.pullRequestId)}/comments`,
3879
- body,
3880
- { actingUserId: input.actingUserId }
3881
- )
3882
- );
3883
- }
3884
- async #updateReviewComment(input) {
3885
- requireGithubConnection(input.connection);
3886
- return parseReviewComment(
3887
- await this.#client.request(
3888
- "PATCH",
3889
- repositoryPath(input.sourceId, `pulls/comments/${requirePositiveId(input.commentId, "review comment")}`),
3890
- { body: input.body },
3891
- { actingUserId: input.actingUserId }
3892
- )
3893
- );
3894
- }
3895
- async #deleteReviewComment(input) {
3896
- requireGithubConnection(input.connection);
3897
- await this.#client.request(
3898
- "DELETE",
3899
- repositoryPath(input.sourceId, `pulls/comments/${requirePositiveId(input.commentId, "review comment")}`),
3900
- void 0,
3901
- { actingUserId: input.actingUserId }
3902
- );
3903
- }
3904
- #requestedReviewers(method, input) {
3905
- requireGithubConnection(input.connection);
3906
- return this.#client.request(
3907
- method,
3908
- `${pullRequestPath(input, input.pullRequestId)}/requested-reviewers`,
3909
- method === "GET" ? void 0 : { users: input.users, teams: input.teams },
3910
- method === "GET" ? void 0 : { actingUserId: input.actingUserId }
3911
- );
3912
- }
49
+ id = "github";
50
+ #client;
51
+ #endpointHost;
52
+ #pollingEnabled;
53
+ #pollingIntervalMs;
54
+ #storage;
55
+ #integrationStorage;
56
+ /** installationId → cached repository listing (TTL-bounded). */
57
+ #installationReposCache = /* @__PURE__ */ new Map();
58
+ /** `orgId:repositoryId` → cached repository access (TTL-bounded). */
59
+ #repositoryAccessCache = /* @__PURE__ */ new Map();
60
+ intake = {
61
+ resolveIntakeDispatch: (input) => this.#resolveIntakeDispatch(input),
62
+ listSources: async ({ orgId, userId }) => {
63
+ const usable = (await this.#client.request("GET", `${API_PREFIX}/github-app/installations`)).installations.filter((installation) => installation.usable && !installation.suspendedAt);
64
+ return (await Promise.all(usable.map(async (installation) => {
65
+ const storedInstallation = await this.versionControl.registerInstallation({
66
+ orgId,
67
+ userId,
68
+ installation: {
69
+ externalId: String(installation.installationId),
70
+ accountName: installation.accountLogin,
71
+ accountType: installation.accountType
72
+ }
73
+ });
74
+ const result = await this.#client.request("GET", `${API_PREFIX}/github-app/installations/${installation.installationId}/repositories`);
75
+ await this.versionControl.registerRepositories({
76
+ orgId,
77
+ installationId: storedInstallation.id,
78
+ repositories: result.repositories.map((repository) => ({
79
+ externalId: String(repository.id),
80
+ slug: repository.fullName,
81
+ defaultBranch: repository.defaultBranch,
82
+ metadata: {
83
+ private: repository.private,
84
+ url: repository.htmlUrl
85
+ }
86
+ }))
87
+ });
88
+ return result.repositories.map((repository) => ({
89
+ repository,
90
+ installation
91
+ }));
92
+ }))).flat().map(({ repository, installation }) => ({
93
+ id: repository.fullName,
94
+ name: repository.fullName,
95
+ type: "repository",
96
+ metadata: {
97
+ installationId: installation.installationId,
98
+ accountLogin: installation.accountLogin,
99
+ accountType: installation.accountType,
100
+ repositoryId: repository.id,
101
+ defaultBranch: repository.defaultBranch,
102
+ private: repository.private,
103
+ url: repository.htmlUrl
104
+ }
105
+ }));
106
+ },
107
+ listItems: async ({ sourceIds, cursor }) => {
108
+ const page = parsePositiveCursor(cursor);
109
+ const pages = await Promise.all(sourceIds.map(async (sourceId) => {
110
+ const connection = {
111
+ type: "app-installation",
112
+ installationId: 1
113
+ };
114
+ const [issues, pullRequests] = await Promise.all([this.#listIssues(connection, sourceId, page), this.#listPullRequests({
115
+ connection,
116
+ sourceId,
117
+ includeDrafts: false,
118
+ cursor: String(page)
119
+ })]);
120
+ return {
121
+ items: [...issues.issues.map((issue) => ({
122
+ source: {
123
+ type: "issue",
124
+ externalId: `${sourceId}:${issue.id}`,
125
+ url: issue.url
126
+ },
127
+ sourceId,
128
+ title: issue.title,
129
+ status: issue.state ?? void 0,
130
+ labels: issue.labels,
131
+ assignee: issue.assignee,
132
+ createdAt: issue.createdAt,
133
+ updatedAt: issue.updatedAt,
134
+ metadata: {
135
+ repository: sourceId,
136
+ number: Number(issue.id),
137
+ author: issue.author
138
+ }
139
+ })), ...pullRequests.pullRequests.map((pullRequest) => ({
140
+ source: {
141
+ type: "pull-request",
142
+ externalId: `${sourceId}:${pullRequest.id}`,
143
+ url: pullRequest.url
144
+ },
145
+ sourceId,
146
+ title: pullRequest.title,
147
+ status: pullRequest.state,
148
+ createdAt: pullRequest.createdAt,
149
+ updatedAt: pullRequest.updatedAt,
150
+ metadata: {
151
+ repository: sourceId,
152
+ number: Number(pullRequest.id),
153
+ author: pullRequest.author,
154
+ baseBranch: pullRequest.baseBranch,
155
+ headBranch: pullRequest.headBranch
156
+ }
157
+ }))],
158
+ hasNextPage: issues.nextCursor !== null || pullRequests.nextCursor !== null
159
+ };
160
+ }));
161
+ return {
162
+ items: pages.flatMap((result) => result.items),
163
+ nextCursor: pages.some((result) => result.hasNextPage) ? String(page + 1) : null
164
+ };
165
+ },
166
+ listIssues: async (input) => {
167
+ requireGithubConnection(input.connection);
168
+ const sourceId = requireSingleSource(input.sourceIds, "GitHub Intake requires exactly one repository source.");
169
+ return this.#listIssues(input.connection, sourceId, parsePositiveCursor(input.cursor), input.labels);
170
+ },
171
+ getIssue: (input) => this.#getIssue(input.connection, input.sourceId, input.issueId),
172
+ createComment: (input) => this.#createIssueComment(input),
173
+ updateIssue: (input) => this.#updateIntakeIssue(input)
174
+ };
175
+ versionControl = {
176
+ initialize: ({ storage }) => {
177
+ this.#storage = storage;
178
+ },
179
+ registerInstallation: ({ orgId, userId, installation }) => this.storage.installations.upsert({
180
+ orgId,
181
+ connectedByUserId: userId,
182
+ externalId: installation.externalId,
183
+ accountName: installation.accountName,
184
+ accountType: installation.accountType,
185
+ providerMetadata: installation.metadata
186
+ }),
187
+ registerRepositories: ({ orgId, installationId, repositories }) => Promise.all(repositories.map((repository) => this.storage.repositories.upsert({
188
+ orgId,
189
+ input: {
190
+ installationId,
191
+ externalId: repository.externalId,
192
+ slug: repository.slug,
193
+ defaultBranch: repository.defaultBranch,
194
+ providerMetadata: repository.metadata
195
+ }
196
+ }))),
197
+ getRepositoryAccess: async ({ orgId, repositoryId }) => {
198
+ const cacheKey = `${orgId}:${repositoryId}`;
199
+ const cached = this.#repositoryAccessCache.get(cacheKey);
200
+ if (cached && cached.expiresAt > Date.now()) return cached.access;
201
+ this.#repositoryAccessCache.delete(cacheKey);
202
+ const repository = await this.storage.repositories.get({
203
+ orgId,
204
+ id: repositoryId
205
+ });
206
+ if (!repository) throw new Error("Version-control repository not found.");
207
+ const cloneUrl = `https://github.com/${repository.slug}.git`;
208
+ const installation = await this.storage.installations.get({
209
+ orgId,
210
+ id: repository.installationId
211
+ });
212
+ if (!installation) throw new Error("Version-control installation not found.");
213
+ const installationId = parsePositiveInteger(installation.externalId);
214
+ if (installationId === null) throw new Error("GitHub installation id is invalid.");
215
+ const repositoryName = splitRepository(repository.slug).repo;
216
+ const access = {
217
+ cloneUrl,
218
+ authorization: {
219
+ scheme: "bearer",
220
+ token: (await this.#client.request("POST", `${API_PREFIX}/github-app/installations/${installationId}/token`, {
221
+ repositories: [repositoryName],
222
+ permissions: REPOSITORY_TOKEN_PERMISSIONS
223
+ })).token
224
+ }
225
+ };
226
+ setBounded(this.#repositoryAccessCache, cacheKey, {
227
+ access,
228
+ expiresAt: Date.now() + REPOSITORY_ACCESS_CACHE_TTL_MS
229
+ });
230
+ return access;
231
+ },
232
+ listPullRequests: (input) => this.#listPullRequests(input),
233
+ getPullRequest: (input) => this.#getPullRequest(input),
234
+ createPullRequest: (input) => this.#createPullRequest(input),
235
+ updatePullRequest: (input) => this.#updatePullRequest(input),
236
+ closePullRequest: (input) => this.#updatePullRequest({
237
+ ...input,
238
+ state: "closed"
239
+ }),
240
+ mergePullRequest: (input) => this.#mergePullRequest(input),
241
+ listComments: (input) => this.#listComments(input),
242
+ createComment: (input) => this.#createComment(input),
243
+ updateComment: (input) => this.#updateComment(input),
244
+ deleteComment: (input) => this.#deleteComment(input),
245
+ listReviews: (input) => this.#listReviews(input),
246
+ getReview: (input) => this.#getReview(input),
247
+ createReview: (input) => this.#createReview(input),
248
+ updateReview: (input) => this.#updateReview(input),
249
+ submitReview: (input) => this.#submitReview(input),
250
+ dismissReview: (input) => this.#dismissReview(input),
251
+ deletePendingReview: (input) => this.#deletePendingReview(input),
252
+ listReviewComments: (input) => this.#listReviewComments(input),
253
+ createReviewComment: (input) => this.#createReviewComment(input),
254
+ updateReviewComment: (input) => this.#updateReviewComment(input),
255
+ deleteReviewComment: (input) => this.#deleteReviewComment(input),
256
+ listRequestedReviewers: (input) => this.#requestedReviewers("GET", input),
257
+ requestReviewers: (input) => this.#requestedReviewers("POST", input),
258
+ removeRequestedReviewers: (input) => this.#requestedReviewers("DELETE", input)
259
+ };
260
+ constructor() {
261
+ const config = platformApiClientConfigFromEnv();
262
+ this.#client = new PlatformApiClient(config);
263
+ this.#endpointHost = new URL(config.baseUrl).host;
264
+ this.#pollingEnabled = process.env.MASTRA_PLATFORM_GITHUB_POLLING_ENABLED?.trim().toLowerCase() !== "false";
265
+ this.#pollingIntervalMs = optionalPositiveIntegerEnv("MASTRA_PLATFORM_GITHUB_POLLING_INTERVAL_MS");
266
+ }
267
+ get storage() {
268
+ if (!this.#storage) throw new Error("PlatformGithubIntegration source-control storage has not been initialized.");
269
+ return this.#storage;
270
+ }
271
+ get sourceControlStorage() {
272
+ return this.storage;
273
+ }
274
+ get integrationStorage() {
275
+ if (!this.#integrationStorage) throw new Error("PlatformGithubIntegration generic storage has not been initialized.");
276
+ return this.#integrationStorage;
277
+ }
278
+ /** Resolve a stored GitHub locator without scanning installations or repositories. */
279
+ async #resolveIntakeDispatch({ orgId, externalSource }) {
280
+ const target = parseGithubExternalTarget(externalSource.externalId);
281
+ if (!target) return null;
282
+ const repository = target.repository.includes("/") ? target.repository : (await this.storage.repositories.findByExternalId({
283
+ orgId,
284
+ externalId: target.repository
285
+ }))?.slug;
286
+ if (!repository) return null;
287
+ return {
288
+ connection: {
289
+ type: "app-installation",
290
+ installationId: 1
291
+ },
292
+ sourceId: repository,
293
+ issueId: target.issueId
294
+ };
295
+ }
296
+ initialize({ storage }) {
297
+ this.#integrationStorage = storage;
298
+ logPlatformInfo("Platform GitHub integration initialized", {
299
+ endpointHost: this.#endpointHost,
300
+ pollingEnabled: this.#pollingEnabled,
301
+ pollingIntervalMs: this.#pollingIntervalMs
302
+ });
303
+ }
304
+ routes(ctx) {
305
+ const ingestFactoryEvent = attachGithubRules(this, ctx);
306
+ return [
307
+ this.#statusRoute(ctx),
308
+ this.#connectRoute(ctx),
309
+ this.#connectUserRoute(ctx),
310
+ ...buildGithubRoutes({
311
+ auth: ctx.auth,
312
+ fleet: ctx.fleet,
313
+ storage: ctx.factoryStorage,
314
+ github: this,
315
+ stateSigner: ctx.stateSigner,
316
+ baseUrl: ctx.baseUrl,
317
+ controller: ctx.controller,
318
+ projects: ctx.storage.projects,
319
+ emitAudit: ctx.hooks?.emitAudit,
320
+ ingestFactoryEvent
321
+ }).filter((route) => route.path !== "/web/github/status" && route.path !== "/web/github/webhook" && !route.path.startsWith("/auth/github/"))
322
+ ];
323
+ }
324
+ #statusRoute(ctx) {
325
+ return registerApiRoute("/web/github/status", {
326
+ method: "GET",
327
+ requiresAuth: false,
328
+ handler: async (c) => {
329
+ await ctx.auth.ensureUser(loose(c));
330
+ const tenant = ctx.auth.tenant(loose(c));
331
+ if (!tenant) return c.json({
332
+ error: "unauthorized",
333
+ reason: "auth_required"
334
+ }, 401);
335
+ if (!tenant.orgId) return c.json({
336
+ enabled: true,
337
+ sandboxEnabled: ctx.fleet.enabled,
338
+ organizationRequired: true,
339
+ connected: false,
340
+ installations: [],
341
+ userConnected: false,
342
+ userGithubUsername: null,
343
+ reason: "organization_required",
344
+ diagnostics: this.diagnostics()
345
+ });
346
+ const [installations, userConnection] = await Promise.all([this.#syncInstallations(tenant.orgId, tenant.userId), this.#fetchUserConnection(tenant.userId)]);
347
+ return c.json({
348
+ enabled: true,
349
+ sandboxEnabled: ctx.fleet.enabled,
350
+ connected: installations.length > 0,
351
+ installations: installations.map((installation) => ({
352
+ installationId: Number(installation.externalId),
353
+ accountLogin: installation.accountName,
354
+ accountType: installation.accountType
355
+ })),
356
+ userConnected: userConnection.connected,
357
+ userGithubUsername: userConnection.githubUsername,
358
+ reason: installations.length > 0 ? "ready" : "not_connected",
359
+ diagnostics: this.diagnostics()
360
+ });
361
+ }
362
+ });
363
+ }
364
+ #connectRoute(ctx) {
365
+ return registerApiRoute("/auth/github/connect", {
366
+ method: "GET",
367
+ requiresAuth: false,
368
+ handler: async (c) => {
369
+ await ctx.auth.ensureUser(loose(c));
370
+ const tenant = ctx.auth.tenant(loose(c));
371
+ if (!tenant?.orgId) return c.json({ error: "unauthorized" }, 401);
372
+ const redirectTo = c.req.query("redirectTo") || c.req.query("return_to") || "/";
373
+ const originator = routeBaseUrl(ctx, c.req.url);
374
+ logPlatformInfo("Starting Platform GitHub connect flow", {
375
+ orgId: tenant.orgId,
376
+ redirectTo,
377
+ originator
378
+ });
379
+ const query = new URLSearchParams({
380
+ action: "install",
381
+ redirectTo,
382
+ originator
383
+ });
384
+ const { url } = await this.#client.request("GET", `${API_PREFIX}/github-app/install-url?${query}`);
385
+ return c.redirect(url);
386
+ }
387
+ });
388
+ }
389
+ #connectUserRoute(ctx) {
390
+ return registerApiRoute("/auth/github/connect-user", {
391
+ method: "GET",
392
+ requiresAuth: false,
393
+ handler: async (c) => {
394
+ await ctx.auth.ensureUser(loose(c));
395
+ const tenant = ctx.auth.tenant(loose(c));
396
+ if (!tenant?.orgId) return c.json({ error: "unauthorized" }, 401);
397
+ const redirectTo = c.req.query("redirectTo") || c.req.query("return_to") || "/";
398
+ const originator = routeBaseUrl(ctx, c.req.url);
399
+ logPlatformInfo("Starting Platform GitHub user authorization flow", {
400
+ orgId: tenant.orgId,
401
+ redirectTo,
402
+ originator
403
+ });
404
+ const query = new URLSearchParams({
405
+ userId: tenant.userId,
406
+ redirectTo,
407
+ originator
408
+ });
409
+ const { url } = await this.#client.request("GET", `${API_PREFIX}/github-app/authenticate?${query}`);
410
+ return c.redirect(url);
411
+ }
412
+ });
413
+ }
414
+ /**
415
+ * Personal GitHub connection status for the acting user. Returns
416
+ * not-connected when the platform predates the user-connection endpoint.
417
+ */
418
+ async #fetchUserConnection(userId) {
419
+ try {
420
+ const connection = await this.#client.request("GET", `${API_PREFIX}/github-app/user-connection?${new URLSearchParams({ userId })}`);
421
+ if (!connection.connected && connection.reason) logPlatformWarn("Platform GitHub user connection verification failed", {
422
+ userId,
423
+ reason: connection.reason
424
+ });
425
+ return connection;
426
+ } catch {
427
+ return {
428
+ connected: false,
429
+ githubUsername: null
430
+ };
431
+ }
432
+ }
433
+ async #syncInstallations(orgId, userId) {
434
+ const usableInstallations = (await this.#client.request("GET", `${API_PREFIX}/github-app/installations`)).installations.filter((installation) => installation.usable && !installation.suspendedAt);
435
+ return Promise.all(usableInstallations.map((installation) => this.versionControl.registerInstallation({
436
+ orgId,
437
+ userId,
438
+ installation: {
439
+ externalId: String(installation.installationId),
440
+ accountName: installation.accountLogin,
441
+ accountType: installation.accountType
442
+ }
443
+ })));
444
+ }
445
+ workers(ctx) {
446
+ if (!this.#pollingEnabled) return [];
447
+ if (!ctx.controller) throw new Error("Platform GitHub event polling requires the mounted Mastra Code controller.");
448
+ return [new PlatformGithubEventWorker({
449
+ client: this.#client,
450
+ controller: ctx.controller,
451
+ github: this,
452
+ storage: ctx.storage.generic,
453
+ ingestFactoryEvent: attachGithubRules(this, ctx),
454
+ intervalMs: this.#pollingIntervalMs
455
+ })];
456
+ }
457
+ sessionTools({ requestContext }) {
458
+ return createGithubSubscriptionTools(requestContext, this);
459
+ }
460
+ async postToolObserver({ toolContext, requestContext }) {
461
+ const pullRequestUrl = parseCreatedPullRequest(toolContext);
462
+ if (!pullRequestUrl || !requestContext) return;
463
+ await subscribeCurrentSessionToPullRequest(requestContext, pullRequestUrl, "auto-gh-pr-create", this);
464
+ }
465
+ diagnostics() {
466
+ return {
467
+ mode: "platform",
468
+ endpointHost: this.#endpointHost,
469
+ polling: {
470
+ enabled: this.#pollingEnabled,
471
+ ...this.#pollingIntervalMs === void 0 ? {} : { intervalMs: this.#pollingIntervalMs }
472
+ }
473
+ };
474
+ }
475
+ async getRepositoryCollaboratorPermission(_installationId, repoFullName, username, signal) {
476
+ let repository;
477
+ try {
478
+ repository = splitRepository(repoFullName);
479
+ } catch {
480
+ return;
481
+ }
482
+ try {
483
+ return (await this.#client.request("GET", `${API_PREFIX}/github/repos/${encodeURIComponent(repository.owner)}/${encodeURIComponent(repository.repo)}/collaborators/${encodeURIComponent(username)}/permission`, void 0, { signal })).permission;
484
+ } catch {
485
+ return;
486
+ }
487
+ }
488
+ async listInstallationRepos(installationId) {
489
+ const cached = this.#installationReposCache.get(installationId);
490
+ if (cached && cached.expiresAt > Date.now()) return cached.repos;
491
+ this.#installationReposCache.delete(installationId);
492
+ const repos = (await this.#client.request("GET", `${API_PREFIX}/github-app/installations/${installationId}/repositories`)).repositories.map((repository) => ({
493
+ ...repository,
494
+ installationId
495
+ }));
496
+ setBounded(this.#installationReposCache, installationId, {
497
+ repos,
498
+ expiresAt: Date.now() + INSTALLATION_REPOS_CACHE_TTL_MS
499
+ });
500
+ return repos;
501
+ }
502
+ async mintInstallationToken(installationId) {
503
+ const repositories = await this.listInstallationRepos(installationId);
504
+ if (repositories.length === 0 || repositories.length > 10) throw new Error("Platform GitHub token minting requires between one and ten installation repositories.");
505
+ return (await this.#client.request("POST", `${API_PREFIX}/github-app/installations/${installationId}/token`, {
506
+ repositories: repositories.map((repository) => repository.name),
507
+ permissions: REPOSITORY_TOKEN_PERMISSIONS
508
+ })).token;
509
+ }
510
+ async addIssueLabels(_installationId, sourceId, issueNumber, labels) {
511
+ return (await this.#client.request("POST", repositoryPath(sourceId, `issues/${issueNumber}/labels`), { labels })).labels;
512
+ }
513
+ getInstallationOctokit(_installationId) {
514
+ return { pulls: { get: async ({ owner, repo, pull_number }) => {
515
+ return { data: { base: { repo: { id: (await this.#client.request("GET", repositoryPath(`${owner}/${repo}`, `pulls/${pull_number}`))).base.repo.id } } } };
516
+ } } };
517
+ }
518
+ async #listIssues(connection, sourceId, page, labels) {
519
+ requireGithubConnection(connection);
520
+ const path = repositoryPath(sourceId, "issues");
521
+ const query = new URLSearchParams({
522
+ state: "open",
523
+ page: String(page),
524
+ per_page: String(PAGE_SIZE)
525
+ });
526
+ const normalizedLabels = normalizeLabels(labels);
527
+ if (normalizedLabels.length > 0) query.set("label", normalizedLabels.join(","));
528
+ const result = await this.#client.request("GET", `${path}?${query}`);
529
+ return {
530
+ issues: result.issues.map((issue) => parseIntakeIssue(sourceId, issue)),
531
+ nextCursor: result.issues.length === PAGE_SIZE ? String(page + 1) : null
532
+ };
533
+ }
534
+ async #getIssue(connection, sourceId, issueId) {
535
+ requireGithubConnection(connection);
536
+ const repository = requireSource(sourceId, "GitHub Intake requires a repository source.");
537
+ const issueNumber = requirePositiveId(issueId, "issue");
538
+ try {
539
+ const [issue, comments] = await Promise.all([this.#client.request("GET", repositoryPath(repository, `issues/${issueNumber}`)), this.#client.request("GET", `${repositoryPath(repository, `issues/${issueNumber}/comments`)}?per_page=100`)]);
540
+ return parseIntakeIssueDetail(repository, issue, comments.comments);
541
+ } catch (error) {
542
+ if (isNotFound(error)) return null;
543
+ throw error;
544
+ }
545
+ }
546
+ async #updateIntakeIssue(input) {
547
+ requireGithubConnection(input.connection);
548
+ const repository = requireSource(input.sourceId, "GitHub Intake requires a repository source.");
549
+ const issueNumber = requirePositiveId(input.issueId, "issue");
550
+ if (input.state.kind === "byName") {
551
+ logPlatformWarn(`Platform GitHub: updateIssue byName is not supported (name=${input.state.name}); ignoring.`);
552
+ return null;
553
+ }
554
+ const targetState = input.state.stateType === "unstarted" || input.state.stateType === "started" ? "open" : "closed";
555
+ const stateReason = targetState === "closed" ? input.state.stateType === "canceled" ? "not_planned" : "completed" : null;
556
+ try {
557
+ await this.#client.request("GET", repositoryPath(repository, `pulls/${issueNumber}`));
558
+ logPlatformWarn(`Platform GitHub: updateIssue rejected — target ${repository}#${issueNumber} is a pull request.`);
559
+ return null;
560
+ } catch (error) {
561
+ if (!isNotFound(error)) throw error;
562
+ }
563
+ try {
564
+ return parseIntakeIssue(repository, await this.#client.request("PATCH", repositoryPath(repository, `issues/${issueNumber}`), {
565
+ state: targetState,
566
+ ...stateReason ? { state_reason: stateReason } : {}
567
+ }, { actingUserId: input.actingUserId }));
568
+ } catch (error) {
569
+ if (isNotFound(error)) return null;
570
+ throw error;
571
+ }
572
+ }
573
+ async #createIssueComment(input) {
574
+ requireGithubConnection(input.connection);
575
+ const repository = requireSource(input.sourceId, "GitHub Intake requires a repository source.");
576
+ const issueNumber = requirePositiveId(input.issueId, "issue");
577
+ try {
578
+ const comment = await this.#client.request("POST", repositoryPath(repository, `issues/${issueNumber}/comments`), { body: input.body }, { actingUserId: input.actingUserId });
579
+ return {
580
+ id: String(comment.id),
581
+ url: comment.htmlUrl
582
+ };
583
+ } catch (error) {
584
+ if (isNotFound(error)) return null;
585
+ throw error;
586
+ }
587
+ }
588
+ async #listPullRequests(input) {
589
+ requireGithubConnection(input.connection);
590
+ const page = parsePositiveCursor(input.cursor);
591
+ const query = new URLSearchParams({
592
+ state: input.state ?? "open",
593
+ page: String(page),
594
+ per_page: String(PAGE_SIZE)
595
+ });
596
+ const result = await this.#client.request("GET", `${repositoryPath(input.sourceId, "pulls")}?${query}`);
597
+ return {
598
+ pullRequests: result.pullRequests.filter((pullRequest) => input.includeDrafts !== false || !pullRequest.draft).map(parsePullRequest),
599
+ nextCursor: result.pullRequests.length === PAGE_SIZE ? String(page + 1) : null
600
+ };
601
+ }
602
+ async #getPullRequest(input) {
603
+ try {
604
+ return parsePullRequest(await this.#client.request("GET", pullRequestPath(input, input.pullRequestId)));
605
+ } catch (error) {
606
+ if (isNotFound(error)) return null;
607
+ throw error;
608
+ }
609
+ }
610
+ async #createPullRequest(input) {
611
+ requireGithubConnection(input.connection);
612
+ return parsePullRequest(await this.#client.request("POST", repositoryPath(input.sourceId, "pulls"), {
613
+ head: input.headBranch,
614
+ base: input.baseBranch,
615
+ title: input.title,
616
+ body: input.body,
617
+ draft: input.draft
618
+ }, { actingUserId: input.actingUserId }));
619
+ }
620
+ async #updatePullRequest(input) {
621
+ return parsePullRequest(await this.#client.request("PATCH", pullRequestPath(input, input.pullRequestId), {
622
+ title: input.title,
623
+ body: input.body === null ? "" : input.body,
624
+ base: input.baseBranch,
625
+ state: input.state
626
+ }, { actingUserId: input.actingUserId }));
627
+ }
628
+ #mergePullRequest(input) {
629
+ return this.#client.request("PUT", `${pullRequestPath(input, input.pullRequestId)}/merge`, {
630
+ commitTitle: input.commitTitle,
631
+ commitMessage: input.commitMessage,
632
+ method: input.method
633
+ }, { actingUserId: input.actingUserId });
634
+ }
635
+ async #listComments(input) {
636
+ const page = parsePositiveCursor(input.cursor);
637
+ const result = await this.#client.request("GET", `${repositoryPath(input.sourceId, `issues/${requirePositiveId(input.pullRequestId, "pull request")}/comments`)}?page=${page}&per_page=${PAGE_SIZE}`);
638
+ return {
639
+ comments: result.comments.map(parseComment),
640
+ nextCursor: result.comments.length === PAGE_SIZE ? String(page + 1) : null
641
+ };
642
+ }
643
+ async #createComment(input) {
644
+ return parseComment(await this.#client.request("POST", repositoryPath(input.sourceId, `issues/${requirePositiveId(input.pullRequestId, "pull request")}/comments`), { body: input.body }, { actingUserId: input.actingUserId }));
645
+ }
646
+ async #updateComment(input) {
647
+ requireGithubConnection(input.connection);
648
+ return parseComment(await this.#client.request("PATCH", repositoryPath(input.sourceId, `issues/comments/${requirePositiveId(input.commentId, "comment")}`), { body: input.body }, { actingUserId: input.actingUserId }));
649
+ }
650
+ async #deleteComment(input) {
651
+ requireGithubConnection(input.connection);
652
+ await this.#client.request("DELETE", repositoryPath(input.sourceId, `issues/comments/${requirePositiveId(input.commentId, "comment")}`), void 0, { actingUserId: input.actingUserId });
653
+ }
654
+ async #listReviews(input) {
655
+ const page = parsePositiveCursor(input.cursor);
656
+ const result = await this.#client.request("GET", `${pullRequestPath(input, input.pullRequestId)}/reviews?page=${page}&per_page=${PAGE_SIZE}`);
657
+ return {
658
+ reviews: result.reviews.map(parseReview),
659
+ nextCursor: result.reviews.length === PAGE_SIZE ? String(page + 1) : null
660
+ };
661
+ }
662
+ async #getReview(input) {
663
+ try {
664
+ return parseReview(await this.#client.request("GET", `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}`));
665
+ } catch (error) {
666
+ if (isNotFound(error)) return null;
667
+ throw error;
668
+ }
669
+ }
670
+ async #createReview(input) {
671
+ return parseReview(await this.#client.request("POST", `${pullRequestPath(input, input.pullRequestId)}/reviews`, {
672
+ body: input.body,
673
+ commitId: input.commitId,
674
+ event: input.event ? reviewEvent(input.event) : void 0
675
+ }, { actingUserId: input.actingUserId }));
676
+ }
677
+ async #updateReview(input) {
678
+ return parseReview(await this.#client.request("PUT", `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}`, { body: input.body }, { actingUserId: input.actingUserId }));
679
+ }
680
+ async #submitReview(input) {
681
+ return parseReview(await this.#client.request("POST", `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}/events`, {
682
+ body: input.body,
683
+ event: reviewEvent(input.event)
684
+ }, { actingUserId: input.actingUserId }));
685
+ }
686
+ async #dismissReview(input) {
687
+ return parseReview(await this.#client.request("PUT", `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}/dismissals`, { message: input.message }, { actingUserId: input.actingUserId }));
688
+ }
689
+ async #deletePendingReview(input) {
690
+ await this.#client.request("DELETE", `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}`, void 0, { actingUserId: input.actingUserId });
691
+ }
692
+ async #listReviewComments(input) {
693
+ const page = parsePositiveCursor(input.cursor);
694
+ const result = await this.#client.request("GET", `${pullRequestPath(input, input.pullRequestId)}/comments?page=${page}&per_page=${PAGE_SIZE}`);
695
+ return {
696
+ comments: result.comments.map(parseReviewComment),
697
+ nextCursor: result.comments.length === PAGE_SIZE ? String(page + 1) : null
698
+ };
699
+ }
700
+ async #createReviewComment(input) {
701
+ let body;
702
+ if (input.replyToId !== void 0) body = {
703
+ body: input.body,
704
+ replyToId: requirePositiveId(input.replyToId, "review comment")
705
+ };
706
+ else {
707
+ if (!input.commitId || !input.path || input.line === void 0 || !input.side) throw new Error("A review comment requires commitId, path, line, and side unless it is a reply.");
708
+ body = {
709
+ body: input.body,
710
+ commitId: input.commitId,
711
+ path: input.path,
712
+ line: input.line,
713
+ side: input.side.toUpperCase(),
714
+ startLine: input.startLine,
715
+ startSide: input.startSide?.toUpperCase()
716
+ };
717
+ }
718
+ return parseReviewComment(await this.#client.request("POST", `${pullRequestPath(input, input.pullRequestId)}/comments`, body, { actingUserId: input.actingUserId }));
719
+ }
720
+ async #updateReviewComment(input) {
721
+ requireGithubConnection(input.connection);
722
+ return parseReviewComment(await this.#client.request("PATCH", repositoryPath(input.sourceId, `pulls/comments/${requirePositiveId(input.commentId, "review comment")}`), { body: input.body }, { actingUserId: input.actingUserId }));
723
+ }
724
+ async #deleteReviewComment(input) {
725
+ requireGithubConnection(input.connection);
726
+ await this.#client.request("DELETE", repositoryPath(input.sourceId, `pulls/comments/${requirePositiveId(input.commentId, "review comment")}`), void 0, { actingUserId: input.actingUserId });
727
+ }
728
+ #requestedReviewers(method, input) {
729
+ requireGithubConnection(input.connection);
730
+ return this.#client.request(method, `${pullRequestPath(input, input.pullRequestId)}/requested-reviewers`, method === "GET" ? void 0 : {
731
+ users: input.users,
732
+ teams: input.teams
733
+ }, method === "GET" ? void 0 : { actingUserId: input.actingUserId });
734
+ }
3913
735
  };
3914
736
  function repositoryPath(sourceId, suffix) {
3915
- const { owner, repo } = splitRepository(sourceId);
3916
- return `${API_PREFIX2}/github/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${suffix}`;
737
+ const { owner, repo } = splitRepository(sourceId);
738
+ return `${API_PREFIX}/github/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${suffix}`;
3917
739
  }
3918
740
  function pullRequestPath(input, pullRequestId) {
3919
- requireGithubConnection(input.connection);
3920
- return repositoryPath(input.sourceId, `pulls/${requirePositiveId(pullRequestId, "pull request")}`);
741
+ requireGithubConnection(input.connection);
742
+ return repositoryPath(input.sourceId, `pulls/${requirePositiveId(pullRequestId, "pull request")}`);
3921
743
  }
3922
744
  function splitRepository(sourceId) {
3923
- const slash = sourceId.indexOf("/");
3924
- if (slash <= 0 || slash === sourceId.length - 1) {
3925
- throw new Error("GitHub capabilities require an owner/repository source.");
3926
- }
3927
- return { owner: sourceId.slice(0, slash), repo: sourceId.slice(slash + 1) };
745
+ const slash = sourceId.indexOf("/");
746
+ if (slash <= 0 || slash === sourceId.length - 1) throw new Error("GitHub capabilities require an owner/repository source.");
747
+ return {
748
+ owner: sourceId.slice(0, slash),
749
+ repo: sourceId.slice(slash + 1)
750
+ };
3928
751
  }
3929
752
  function parseIntakeIssue(sourceId, issue) {
3930
- return {
3931
- id: String(issue.number),
3932
- identifier: `#${issue.number}`,
3933
- title: issue.title,
3934
- url: issue.htmlUrl,
3935
- author: issue.user?.login ?? null,
3936
- state: issue.state,
3937
- stateType: issue.state,
3938
- priority: null,
3939
- assignee: issue.assignees[0] ?? null,
3940
- source: sourceId,
3941
- labels: issue.labels,
3942
- commentCount: issue.commentCount,
3943
- createdAt: issue.createdAt,
3944
- updatedAt: issue.updatedAt
3945
- };
753
+ return {
754
+ id: String(issue.number),
755
+ identifier: `#${issue.number}`,
756
+ title: issue.title,
757
+ url: issue.htmlUrl,
758
+ author: issue.user?.login ?? null,
759
+ state: issue.state,
760
+ stateType: issue.state,
761
+ priority: null,
762
+ assignee: issue.assignees[0] ?? null,
763
+ source: sourceId,
764
+ labels: issue.labels,
765
+ commentCount: issue.commentCount,
766
+ createdAt: issue.createdAt,
767
+ updatedAt: issue.updatedAt
768
+ };
3946
769
  }
3947
770
  function parseIntakeIssueDetail(sourceId, issue, comments) {
3948
- return {
3949
- ...parseIntakeIssue(sourceId, issue),
3950
- description: issue.body?.trim() ? issue.body : null,
3951
- comments: comments.map((comment) => ({
3952
- author: comment.user?.login ?? null,
3953
- body: comment.body,
3954
- createdAt: comment.createdAt
3955
- }))
3956
- };
3957
- }
3958
- function parsePullRequest2(pullRequest) {
3959
- return {
3960
- id: String(pullRequest.number),
3961
- title: pullRequest.title,
3962
- url: pullRequest.htmlUrl,
3963
- author: pullRequest.user?.login ?? null,
3964
- body: pullRequest.body?.trim() ? pullRequest.body : null,
3965
- state: pullRequest.state,
3966
- draft: pullRequest.draft,
3967
- merged: pullRequest.merged,
3968
- mergeable: pullRequest.mergeable,
3969
- baseBranch: pullRequest.base.ref,
3970
- headBranch: pullRequest.head.ref,
3971
- headSha: pullRequest.head.sha,
3972
- createdAt: pullRequest.createdAt,
3973
- updatedAt: pullRequest.updatedAt
3974
- };
771
+ return {
772
+ ...parseIntakeIssue(sourceId, issue),
773
+ description: issue.body?.trim() ? issue.body : null,
774
+ comments: comments.map((comment) => ({
775
+ author: comment.user?.login ?? null,
776
+ body: comment.body,
777
+ createdAt: comment.createdAt
778
+ }))
779
+ };
780
+ }
781
+ function parsePullRequest(pullRequest) {
782
+ return {
783
+ id: String(pullRequest.number),
784
+ title: pullRequest.title,
785
+ url: pullRequest.htmlUrl,
786
+ author: pullRequest.user?.login ?? null,
787
+ body: pullRequest.body?.trim() ? pullRequest.body : null,
788
+ state: pullRequest.state,
789
+ draft: pullRequest.draft,
790
+ merged: pullRequest.merged,
791
+ mergeable: pullRequest.mergeable,
792
+ baseBranch: pullRequest.base.ref,
793
+ headBranch: pullRequest.head.ref,
794
+ headSha: pullRequest.head.sha,
795
+ createdAt: pullRequest.createdAt,
796
+ updatedAt: pullRequest.updatedAt
797
+ };
3975
798
  }
3976
799
  function parseComment(comment) {
3977
- return {
3978
- id: String(comment.id),
3979
- url: comment.htmlUrl,
3980
- author: comment.user?.login ?? null,
3981
- body: comment.body,
3982
- createdAt: comment.createdAt,
3983
- updatedAt: comment.updatedAt
3984
- };
800
+ return {
801
+ id: String(comment.id),
802
+ url: comment.htmlUrl,
803
+ author: comment.user?.login ?? null,
804
+ body: comment.body,
805
+ createdAt: comment.createdAt,
806
+ updatedAt: comment.updatedAt
807
+ };
3985
808
  }
3986
809
  function parseReview(review) {
3987
- const states = {
3988
- PENDING: "pending",
3989
- COMMENTED: "commented",
3990
- APPROVED: "approved",
3991
- CHANGES_REQUESTED: "changes-requested",
3992
- DISMISSED: "dismissed"
3993
- };
3994
- return {
3995
- id: String(review.id),
3996
- url: review.htmlUrl,
3997
- author: review.user?.login ?? null,
3998
- body: review.body?.trim() ? review.body : null,
3999
- state: states[review.state],
4000
- commitId: review.commitId,
4001
- submittedAt: review.submittedAt
4002
- };
810
+ return {
811
+ id: String(review.id),
812
+ url: review.htmlUrl,
813
+ author: review.user?.login ?? null,
814
+ body: review.body?.trim() ? review.body : null,
815
+ state: {
816
+ PENDING: "pending",
817
+ COMMENTED: "commented",
818
+ APPROVED: "approved",
819
+ CHANGES_REQUESTED: "changes-requested",
820
+ DISMISSED: "dismissed"
821
+ }[review.state],
822
+ commitId: review.commitId,
823
+ submittedAt: review.submittedAt
824
+ };
4003
825
  }
4004
826
  function parseReviewComment(comment) {
4005
- return {
4006
- ...parseComment(comment),
4007
- path: comment.path,
4008
- line: comment.line,
4009
- side: comment.side?.toLowerCase(),
4010
- commitId: comment.commitId,
4011
- replyToId: comment.replyToId === null ? null : String(comment.replyToId)
4012
- };
827
+ return {
828
+ ...parseComment(comment),
829
+ path: comment.path,
830
+ line: comment.line,
831
+ side: comment.side?.toLowerCase(),
832
+ commitId: comment.commitId,
833
+ replyToId: comment.replyToId === null ? null : String(comment.replyToId)
834
+ };
4013
835
  }
4014
836
  function requireGithubConnection(connection) {
4015
- if (connection.type !== "app-installation" && connection.type !== "oauth") {
4016
- throw new Error("GitHub capabilities require a GitHub connection.");
4017
- }
837
+ if (connection.type !== "app-installation" && connection.type !== "oauth") throw new Error("GitHub capabilities require a GitHub connection.");
4018
838
  }
4019
839
  function requireSingleSource(sourceIds, message) {
4020
- if (sourceIds.length !== 1) throw new Error(message);
4021
- return sourceIds[0];
840
+ if (sourceIds.length !== 1) throw new Error(message);
841
+ return sourceIds[0];
4022
842
  }
4023
843
  function requireSource(sourceId, message) {
4024
- if (!sourceId) throw new Error(message);
4025
- return sourceId;
844
+ if (!sourceId) throw new Error(message);
845
+ return sourceId;
4026
846
  }
4027
847
  function normalizeLabels(labels) {
4028
- return [...new Set((labels ?? []).map((label) => label.trim()).filter(Boolean))];
848
+ return [...new Set((labels ?? []).map((label) => label.trim()).filter(Boolean))];
4029
849
  }
4030
850
  function parsePositiveCursor(cursor) {
4031
- if (cursor === void 0) return 1;
4032
- const parsed = parsePositiveInteger(cursor);
4033
- if (parsed === null) throw new Error("GitHub cursor must be a positive page number.");
4034
- return parsed;
851
+ if (cursor === void 0) return 1;
852
+ const parsed = parsePositiveInteger(cursor);
853
+ if (parsed === null) throw new Error("GitHub cursor must be a positive page number.");
854
+ return parsed;
4035
855
  }
4036
856
  function parsePositiveInteger(value) {
4037
- if (!/^\d+$/.test(value)) return null;
4038
- const parsed = Number(value);
4039
- return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
857
+ if (!/^\d+$/.test(value)) return null;
858
+ const parsed = Number(value);
859
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
4040
860
  }
4041
861
  function parseGithubExternalTarget(externalId) {
4042
- const match = externalId.match(/^(.+\/.+):(\d+)$/) ?? externalId.match(/^github:(\d+):(?:issue|pull-request):(\d+)$/) ?? externalId.match(/^(\d+):(\d+)$/);
4043
- if (!match?.[1] || !match[2] || parsePositiveInteger(match[2]) === null) return null;
4044
- return { repository: match[1], issueId: match[2] };
862
+ const match = externalId.match(/^(.+\/.+):(\d+)$/) ?? externalId.match(/^github:(\d+):(?:issue|pull-request):(\d+)$/) ?? externalId.match(/^(\d+):(\d+)$/);
863
+ if (!match?.[1] || !match[2] || parsePositiveInteger(match[2]) === null) return null;
864
+ return {
865
+ repository: match[1],
866
+ issueId: match[2]
867
+ };
4045
868
  }
4046
869
  function optionalPositiveIntegerEnv(name) {
4047
- const value = process.env[name]?.trim();
4048
- if (!value) return void 0;
4049
- const parsed = parsePositiveInteger(value);
4050
- if (parsed === null) throw new Error(`${name} must be a positive integer.`);
4051
- return parsed;
870
+ const value = process.env[name]?.trim();
871
+ if (!value) return void 0;
872
+ const parsed = parsePositiveInteger(value);
873
+ if (parsed === null) throw new Error(`${name} must be a positive integer.`);
874
+ return parsed;
4052
875
  }
4053
876
  function requirePositiveId(value, resource) {
4054
- const parsed = parsePositiveInteger(value);
4055
- if (parsed === null) throw new Error(`GitHub ${resource} id must be a positive integer.`);
4056
- return parsed;
877
+ const parsed = parsePositiveInteger(value);
878
+ if (parsed === null) throw new Error(`GitHub ${resource} id must be a positive integer.`);
879
+ return parsed;
4057
880
  }
4058
881
  function reviewEvent(event) {
4059
- if (event === "approve") return "APPROVE";
4060
- if (event === "request-changes") return "REQUEST_CHANGES";
4061
- return "COMMENT";
882
+ if (event === "approve") return "APPROVE";
883
+ if (event === "request-changes") return "REQUEST_CHANGES";
884
+ return "COMMENT";
4062
885
  }
4063
886
  function isNotFound(error) {
4064
- return error instanceof PlatformApiError && error.status === 404;
887
+ return error instanceof PlatformApiError && error.status === 404;
4065
888
  }
4066
- export {
4067
- PlatformGithubIntegration
4068
- };
889
+ //#endregion
890
+ export { PlatformGithubIntegration };
891
+
4069
892
  //# sourceMappingURL=integration.js.map