@mastra/factory 0.0.0 → 0.1.0-alpha.3

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 (287) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE.md +30 -0
  3. package/dist/auth.d.ts +181 -0
  4. package/dist/auth.d.ts.map +1 -0
  5. package/dist/auth.js +370 -0
  6. package/dist/auth.js.map +1 -0
  7. package/dist/capabilities/connection.d.ts +9 -0
  8. package/dist/capabilities/connection.d.ts.map +1 -0
  9. package/dist/capabilities/connection.js +1 -0
  10. package/dist/capabilities/connection.js.map +1 -0
  11. package/dist/capabilities/intake.d.ts +93 -0
  12. package/dist/capabilities/intake.d.ts.map +1 -0
  13. package/dist/capabilities/intake.js +1 -0
  14. package/dist/capabilities/intake.js.map +1 -0
  15. package/dist/capabilities/version-control.d.ts +239 -0
  16. package/dist/capabilities/version-control.d.ts.map +1 -0
  17. package/dist/capabilities/version-control.js +1 -0
  18. package/dist/capabilities/version-control.js.map +1 -0
  19. package/dist/factory.d.ts +145 -0
  20. package/dist/factory.d.ts.map +1 -0
  21. package/dist/factory.js +38245 -0
  22. package/dist/factory.js.map +1 -0
  23. package/dist/index.d.ts +3 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +38245 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/integrations/base.d.ts +197 -0
  28. package/dist/integrations/base.d.ts.map +1 -0
  29. package/dist/integrations/base.js +1 -0
  30. package/dist/integrations/base.js.map +1 -0
  31. package/dist/integrations/github/config.d.ts +60 -0
  32. package/dist/integrations/github/config.d.ts.map +1 -0
  33. package/dist/integrations/github/config.js +28 -0
  34. package/dist/integrations/github/config.js.map +1 -0
  35. package/dist/integrations/github/factory-session.d.ts +12 -0
  36. package/dist/integrations/github/factory-session.d.ts.map +1 -0
  37. package/dist/integrations/github/factory-session.js +41 -0
  38. package/dist/integrations/github/factory-session.js.map +1 -0
  39. package/dist/integrations/github/integration.d.ts +191 -0
  40. package/dist/integrations/github/integration.d.ts.map +1 -0
  41. package/dist/integrations/github/integration.js +3001 -0
  42. package/dist/integrations/github/integration.js.map +1 -0
  43. package/dist/integrations/github/issue-triage.d.ts +27 -0
  44. package/dist/integrations/github/issue-triage.d.ts.map +1 -0
  45. package/dist/integrations/github/issue-triage.js +82 -0
  46. package/dist/integrations/github/issue-triage.js.map +1 -0
  47. package/dist/integrations/github/project-lock.d.ts +78 -0
  48. package/dist/integrations/github/project-lock.d.ts.map +1 -0
  49. package/dist/integrations/github/project-lock.js +70 -0
  50. package/dist/integrations/github/project-lock.js.map +1 -0
  51. package/dist/integrations/github/provenance.d.ts +27 -0
  52. package/dist/integrations/github/provenance.d.ts.map +1 -0
  53. package/dist/integrations/github/provenance.js +104 -0
  54. package/dist/integrations/github/provenance.js.map +1 -0
  55. package/dist/integrations/github/routes.d.ts +72 -0
  56. package/dist/integrations/github/routes.d.ts.map +1 -0
  57. package/dist/integrations/github/routes.js +1834 -0
  58. package/dist/integrations/github/routes.js.map +1 -0
  59. package/dist/integrations/github/sandbox.d.ts +268 -0
  60. package/dist/integrations/github/sandbox.d.ts.map +1 -0
  61. package/dist/integrations/github/sandbox.js +381 -0
  62. package/dist/integrations/github/sandbox.js.map +1 -0
  63. package/dist/integrations/github/session-subscriptions.d.ts +23 -0
  64. package/dist/integrations/github/session-subscriptions.d.ts.map +1 -0
  65. package/dist/integrations/github/session-subscriptions.js +190 -0
  66. package/dist/integrations/github/session-subscriptions.js.map +1 -0
  67. package/dist/integrations/github/subscriptions.d.ts +54 -0
  68. package/dist/integrations/github/subscriptions.d.ts.map +1 -0
  69. package/dist/integrations/github/subscriptions.js +70 -0
  70. package/dist/integrations/github/subscriptions.js.map +1 -0
  71. package/dist/integrations/github/webhook.d.ts +87 -0
  72. package/dist/integrations/github/webhook.d.ts.map +1 -0
  73. package/dist/integrations/github/webhook.js +381 -0
  74. package/dist/integrations/github/webhook.js.map +1 -0
  75. package/dist/integrations/linear/agent-tools.d.ts +34 -0
  76. package/dist/integrations/linear/agent-tools.d.ts.map +1 -0
  77. package/dist/integrations/linear/agent-tools.js +108 -0
  78. package/dist/integrations/linear/agent-tools.js.map +1 -0
  79. package/dist/integrations/linear/integration.d.ts +233 -0
  80. package/dist/integrations/linear/integration.d.ts.map +1 -0
  81. package/dist/integrations/linear/integration.js +962 -0
  82. package/dist/integrations/linear/integration.js.map +1 -0
  83. package/dist/integrations/linear/routes.d.ts +61 -0
  84. package/dist/integrations/linear/routes.d.ts.map +1 -0
  85. package/dist/integrations/linear/routes.js +242 -0
  86. package/dist/integrations/linear/routes.js.map +1 -0
  87. package/dist/integrations/linear/storage.d.ts +65 -0
  88. package/dist/integrations/linear/storage.d.ts.map +1 -0
  89. package/dist/integrations/linear/storage.js +1 -0
  90. package/dist/integrations/linear/storage.js.map +1 -0
  91. package/dist/integrations/platform/api-client.d.ts +24 -0
  92. package/dist/integrations/platform/api-client.d.ts.map +1 -0
  93. package/dist/integrations/platform/api-client.js +153 -0
  94. package/dist/integrations/platform/api-client.js.map +1 -0
  95. package/dist/integrations/platform/github/event-worker.d.ts +44 -0
  96. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -0
  97. package/dist/integrations/platform/github/event-worker.js +585 -0
  98. package/dist/integrations/platform/github/event-worker.js.map +1 -0
  99. package/dist/integrations/platform/github/integration.d.ts +36 -0
  100. package/dist/integrations/platform/github/integration.d.ts.map +1 -0
  101. package/dist/integrations/platform/github/integration.js +3253 -0
  102. package/dist/integrations/platform/github/integration.js.map +1 -0
  103. package/dist/integrations/platform/linear/integration.d.ts +46 -0
  104. package/dist/integrations/platform/linear/integration.d.ts.map +1 -0
  105. package/dist/integrations/platform/linear/integration.js +891 -0
  106. package/dist/integrations/platform/linear/integration.js.map +1 -0
  107. package/dist/integrations/workos/integration.d.ts +39 -0
  108. package/dist/integrations/workos/integration.d.ts.map +1 -0
  109. package/dist/integrations/workos/integration.js +96 -0
  110. package/dist/integrations/workos/integration.js.map +1 -0
  111. package/dist/routes/config.d.ts +220 -0
  112. package/dist/routes/config.d.ts.map +1 -0
  113. package/dist/routes/config.js +770 -0
  114. package/dist/routes/config.js.map +1 -0
  115. package/dist/routes/fs.d.ts +105 -0
  116. package/dist/routes/fs.d.ts.map +1 -0
  117. package/dist/routes/fs.js +294 -0
  118. package/dist/routes/fs.js.map +1 -0
  119. package/dist/routes/intake.d.ts +23 -0
  120. package/dist/routes/intake.d.ts.map +1 -0
  121. package/dist/routes/intake.js +179 -0
  122. package/dist/routes/intake.js.map +1 -0
  123. package/dist/routes/oauth.d.ts +43 -0
  124. package/dist/routes/oauth.d.ts.map +1 -0
  125. package/dist/routes/oauth.js +25058 -0
  126. package/dist/routes/oauth.js.map +1 -0
  127. package/dist/routes/projects.d.ts +19 -0
  128. package/dist/routes/projects.d.ts.map +1 -0
  129. package/dist/routes/projects.js +395 -0
  130. package/dist/routes/projects.js.map +1 -0
  131. package/dist/routes/provider-credentials.d.ts +81 -0
  132. package/dist/routes/provider-credentials.d.ts.map +1 -0
  133. package/dist/routes/provider-credentials.js +68 -0
  134. package/dist/routes/provider-credentials.js.map +1 -0
  135. package/dist/routes/route.d.ts +48 -0
  136. package/dist/routes/route.d.ts.map +1 -0
  137. package/dist/routes/route.js +11 -0
  138. package/dist/routes/route.js.map +1 -0
  139. package/dist/routes/skills.d.ts +30 -0
  140. package/dist/routes/skills.d.ts.map +1 -0
  141. package/dist/routes/skills.js +181 -0
  142. package/dist/routes/skills.js.map +1 -0
  143. package/dist/routes/surface.d.ts +83 -0
  144. package/dist/routes/surface.d.ts.map +1 -0
  145. package/dist/routes/surface.js +28519 -0
  146. package/dist/routes/surface.js.map +1 -0
  147. package/dist/routes/tenant-credentials.d.ts +74 -0
  148. package/dist/routes/tenant-credentials.d.ts.map +1 -0
  149. package/dist/routes/tenant-credentials.js +181 -0
  150. package/dist/routes/tenant-credentials.js.map +1 -0
  151. package/dist/routes/work-items.d.ts +40 -0
  152. package/dist/routes/work-items.d.ts.map +1 -0
  153. package/dist/routes/work-items.js +902 -0
  154. package/dist/routes/work-items.js.map +1 -0
  155. package/dist/rules/binding-context.d.ts +5 -0
  156. package/dist/rules/binding-context.d.ts.map +1 -0
  157. package/dist/rules/binding-context.js +40 -0
  158. package/dist/rules/binding-context.js.map +1 -0
  159. package/dist/rules/defaults.d.ts +9 -0
  160. package/dist/rules/defaults.d.ts.map +1 -0
  161. package/dist/rules/defaults.js +334 -0
  162. package/dist/rules/defaults.js.map +1 -0
  163. package/dist/rules/dispatcher.d.ts +40 -0
  164. package/dist/rules/dispatcher.d.ts.map +1 -0
  165. package/dist/rules/dispatcher.js +695 -0
  166. package/dist/rules/dispatcher.js.map +1 -0
  167. package/dist/rules/github-service.d.ts +29 -0
  168. package/dist/rules/github-service.d.ts.map +1 -0
  169. package/dist/rules/github-service.js +474 -0
  170. package/dist/rules/github-service.js.map +1 -0
  171. package/dist/rules/index.d.ts +7 -0
  172. package/dist/rules/index.d.ts.map +1 -0
  173. package/dist/rules/index.js +583 -0
  174. package/dist/rules/index.js.map +1 -0
  175. package/dist/rules/linear-service.d.ts +27 -0
  176. package/dist/rules/linear-service.d.ts.map +1 -0
  177. package/dist/rules/linear-service.js +343 -0
  178. package/dist/rules/linear-service.js.map +1 -0
  179. package/dist/rules/processor.d.ts +54 -0
  180. package/dist/rules/processor.d.ts.map +1 -0
  181. package/dist/rules/processor.js +629 -0
  182. package/dist/rules/processor.js.map +1 -0
  183. package/dist/rules/resolve.d.ts +17 -0
  184. package/dist/rules/resolve.d.ts.map +1 -0
  185. package/dist/rules/resolve.js +27 -0
  186. package/dist/rules/resolve.js.map +1 -0
  187. package/dist/rules/start-coordinator.d.ts +58 -0
  188. package/dist/rules/start-coordinator.d.ts.map +1 -0
  189. package/dist/rules/start-coordinator.js +136 -0
  190. package/dist/rules/start-coordinator.js.map +1 -0
  191. package/dist/rules/tools.d.ts +10 -0
  192. package/dist/rules/tools.d.ts.map +1 -0
  193. package/dist/rules/tools.js +93 -0
  194. package/dist/rules/tools.js.map +1 -0
  195. package/dist/rules/transition-service.d.ts +32 -0
  196. package/dist/rules/transition-service.d.ts.map +1 -0
  197. package/dist/rules/transition-service.js +474 -0
  198. package/dist/rules/transition-service.js.map +1 -0
  199. package/dist/rules/types.d.ts +225 -0
  200. package/dist/rules/types.d.ts.map +1 -0
  201. package/dist/rules/types.js +33 -0
  202. package/dist/rules/types.js.map +1 -0
  203. package/dist/rules/validation.d.ts +11 -0
  204. package/dist/rules/validation.d.ts.map +1 -0
  205. package/dist/rules/validation.js +310 -0
  206. package/dist/rules/validation.js.map +1 -0
  207. package/dist/sandbox/fleet.d.ts +208 -0
  208. package/dist/sandbox/fleet.d.ts.map +1 -0
  209. package/dist/sandbox/fleet.js +259 -0
  210. package/dist/sandbox/fleet.js.map +1 -0
  211. package/dist/sandbox/reattach.d.ts +3 -0
  212. package/dist/sandbox/reattach.d.ts.map +1 -0
  213. package/dist/sandbox/reattach.js +9 -0
  214. package/dist/sandbox/reattach.js.map +1 -0
  215. package/dist/server-error.d.ts +12 -0
  216. package/dist/server-error.d.ts.map +1 -0
  217. package/dist/server-error.js +20 -0
  218. package/dist/server-error.js.map +1 -0
  219. package/dist/skills/service.d.ts +48 -0
  220. package/dist/skills/service.d.ts.map +1 -0
  221. package/dist/skills/service.js +45 -0
  222. package/dist/skills/service.js.map +1 -0
  223. package/dist/spa-static.d.ts +34 -0
  224. package/dist/spa-static.d.ts.map +1 -0
  225. package/dist/spa-static.js +73 -0
  226. package/dist/spa-static.js.map +1 -0
  227. package/dist/state-signing.d.ts +48 -0
  228. package/dist/state-signing.d.ts.map +1 -0
  229. package/dist/state-signing.js +48 -0
  230. package/dist/state-signing.js.map +1 -0
  231. package/dist/storage/domains/audit/agent-audit.d.ts +27 -0
  232. package/dist/storage/domains/audit/agent-audit.d.ts.map +1 -0
  233. package/dist/storage/domains/audit/agent-audit.js +65 -0
  234. package/dist/storage/domains/audit/agent-audit.js.map +1 -0
  235. package/dist/storage/domains/audit/base.d.ts +140 -0
  236. package/dist/storage/domains/audit/base.d.ts.map +1 -0
  237. package/dist/storage/domains/audit/base.js +127 -0
  238. package/dist/storage/domains/audit/base.js.map +1 -0
  239. package/dist/storage/domains/audit/domain.d.ts +69 -0
  240. package/dist/storage/domains/audit/domain.d.ts.map +1 -0
  241. package/dist/storage/domains/audit/domain.js +165 -0
  242. package/dist/storage/domains/audit/domain.js.map +1 -0
  243. package/dist/storage/domains/credentials/base.d.ts +134 -0
  244. package/dist/storage/domains/credentials/base.d.ts.map +1 -0
  245. package/dist/storage/domains/credentials/base.js +257 -0
  246. package/dist/storage/domains/credentials/base.js.map +1 -0
  247. package/dist/storage/domains/intake/base.d.ts +38 -0
  248. package/dist/storage/domains/intake/base.d.ts.map +1 -0
  249. package/dist/storage/domains/intake/base.js +62 -0
  250. package/dist/storage/domains/intake/base.js.map +1 -0
  251. package/dist/storage/domains/integrations/base.d.ts +126 -0
  252. package/dist/storage/domains/integrations/base.d.ts.map +1 -0
  253. package/dist/storage/domains/integrations/base.js +252 -0
  254. package/dist/storage/domains/integrations/base.js.map +1 -0
  255. package/dist/storage/domains/model-packs/base.d.ts +49 -0
  256. package/dist/storage/domains/model-packs/base.d.ts.map +1 -0
  257. package/dist/storage/domains/model-packs/base.js +95 -0
  258. package/dist/storage/domains/model-packs/base.js.map +1 -0
  259. package/dist/storage/domains/projects/base.d.ts +55 -0
  260. package/dist/storage/domains/projects/base.d.ts.map +1 -0
  261. package/dist/storage/domains/projects/base.js +99 -0
  262. package/dist/storage/domains/projects/base.js.map +1 -0
  263. package/dist/storage/domains/queue-health/base.d.ts +52 -0
  264. package/dist/storage/domains/queue-health/base.d.ts.map +1 -0
  265. package/dist/storage/domains/queue-health/base.js +87 -0
  266. package/dist/storage/domains/queue-health/base.js.map +1 -0
  267. package/dist/storage/domains/source-control/base.d.ts +288 -0
  268. package/dist/storage/domains/source-control/base.d.ts.map +1 -0
  269. package/dist/storage/domains/source-control/base.js +722 -0
  270. package/dist/storage/domains/source-control/base.js.map +1 -0
  271. package/dist/storage/domains/source-control/inmemory.d.ts +158 -0
  272. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -0
  273. package/dist/storage/domains/source-control/inmemory.js +348 -0
  274. package/dist/storage/domains/source-control/inmemory.js.map +1 -0
  275. package/dist/storage/domains/work-items/base.d.ts +412 -0
  276. package/dist/storage/domains/work-items/base.d.ts.map +1 -0
  277. package/dist/storage/domains/work-items/base.js +1174 -0
  278. package/dist/storage/domains/work-items/base.js.map +1 -0
  279. package/dist/storage/domains/work-items/metrics.d.ts +101 -0
  280. package/dist/storage/domains/work-items/metrics.d.ts.map +1 -0
  281. package/dist/storage/domains/work-items/metrics.js +203 -0
  282. package/dist/storage/domains/work-items/metrics.js.map +1 -0
  283. package/dist/workspace.d.ts +20 -0
  284. package/dist/workspace.d.ts.map +1 -0
  285. package/dist/workspace.js +364 -0
  286. package/dist/workspace.js.map +1 -0
  287. package/package.json +19 -19
@@ -0,0 +1,3253 @@
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";
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/project-lock.ts
55
+ import { createHash } from "crypto";
56
+ var inProcessLocks = /* @__PURE__ */ new Map();
57
+ function hashKey(key) {
58
+ const digest = createHash("sha256").update(key).digest();
59
+ const a = digest.readInt32BE(0);
60
+ const b = digest.readInt32BE(4);
61
+ return [a, b];
62
+ }
63
+ function withProjectLock(options) {
64
+ const { key, storage, fn, pool } = options;
65
+ const prev = inProcessLocks.get(key) ?? Promise.resolve();
66
+ const run = () => withDbAdvisoryLock({ key, storage, fn, pool });
67
+ const next = prev.then(run, run);
68
+ const tail = next.then(
69
+ () => void 0,
70
+ () => void 0
71
+ );
72
+ inProcessLocks.set(key, tail);
73
+ void tail.then(() => {
74
+ if (inProcessLocks.get(key) === tail) {
75
+ inProcessLocks.delete(key);
76
+ }
77
+ });
78
+ return next;
79
+ }
80
+ async function withDbAdvisoryLock(options) {
81
+ const { key, storage, fn, pool } = options;
82
+ if (process.env.MASTRACODE_DISTRIBUTED_LOCK === "0") {
83
+ return fn();
84
+ }
85
+ if (pool) return advisoryLockOver(pool, key, fn);
86
+ if (typeof storage?.withDistributedLock !== "function") {
87
+ return fn();
88
+ }
89
+ return storage.withDistributedLock(key, fn);
90
+ }
91
+ async function advisoryLockOver(pool, key, fn) {
92
+ const [k1, k2] = hashKey(key);
93
+ const client = await pool.connect();
94
+ try {
95
+ await client.query("BEGIN");
96
+ await client.query("SELECT pg_advisory_xact_lock($1, $2)", [k1, k2]);
97
+ try {
98
+ const result = await fn();
99
+ await client.query("COMMIT");
100
+ return result;
101
+ } catch (err) {
102
+ await client.query("ROLLBACK");
103
+ throw err;
104
+ }
105
+ } finally {
106
+ client.release();
107
+ }
108
+ }
109
+
110
+ // src/integrations/github/sandbox.ts
111
+ import { createHash as createHash2 } from "crypto";
112
+ function bindingStore(row, storage) {
113
+ return {
114
+ sandboxId: row.sandboxId,
115
+ setSandboxId: (id) => id === null ? storage.clearBinding({ id: row.id }) : storage.setSandboxId({ id: row.id, sandboxId: id }),
116
+ clear: () => storage.clearBinding({ id: row.id })
117
+ };
118
+ }
119
+ async function ensureProjectSandbox(options) {
120
+ const { fleet, row, storage, onProgress } = options;
121
+ return fleet.ensureSandbox(bindingStore(row, storage), onProgress);
122
+ }
123
+ async function teardownProjectSandbox(options) {
124
+ const { fleet, row, storage, sandbox } = options;
125
+ return fleet.teardownSandbox(bindingStore(row, storage), sandbox);
126
+ }
127
+ function shellQuote(value) {
128
+ return `'` + value.split(`'`).join(`'\\''`) + `'`;
129
+ }
130
+ async function sh(sandbox, script) {
131
+ return sandbox.executeCommand("sh", ["-c", script]);
132
+ }
133
+ var MaterializeError = class extends Error {
134
+ constructor(message, code) {
135
+ super(message);
136
+ this.code = code;
137
+ this.name = "MaterializeError";
138
+ }
139
+ code;
140
+ };
141
+ function tokenUrl(repoFullName, token) {
142
+ return `https://x-access-token:${token}@github.com/${repoFullName}.git`;
143
+ }
144
+ function cleanUrl(repoFullName) {
145
+ return `https://github.com/${repoFullName}.git`;
146
+ }
147
+ async function materializeRepo(options) {
148
+ const { row: sandboxRow, repoInfo, sandbox, token, storage, onProgress } = options;
149
+ const workdir = sandboxRow.sandboxWorkdir;
150
+ const repo = repoInfo.repoFullName;
151
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) {
152
+ throw new MaterializeError(`Refusing to materialize: invalid repo full name '${repo}'.`, "clone-failed");
153
+ }
154
+ if (!/^[A-Za-z0-9_./-]+$/.test(repoInfo.defaultBranch)) {
155
+ throw new MaterializeError(
156
+ `Refusing to materialize: invalid default branch '${repoInfo.defaultBranch}'.`,
157
+ "clone-failed"
158
+ );
159
+ }
160
+ const gitVersion = await sh(sandbox, "git --version");
161
+ if (gitVersion.exitCode !== 0) {
162
+ throw new MaterializeError(
163
+ "git is not installed in the sandbox. The sandbox template must include git.",
164
+ "git-missing"
165
+ );
166
+ }
167
+ const authUrl = tokenUrl(repo, token);
168
+ const alreadyMaterialized = Boolean(sandboxRow.materializedAt) || await hasExistingCheckout(sandbox, workdir, repo);
169
+ try {
170
+ if (!alreadyMaterialized) {
171
+ reportProgress(onProgress, {
172
+ phase: "cloning",
173
+ message: `Cloning ${repo} (first open can take a minute)\u2026`
174
+ });
175
+ const clone = await sh(
176
+ sandbox,
177
+ `git clone --depth=1 --single-branch --branch ${shellQuote(repoInfo.defaultBranch)} ${shellQuote(authUrl)} ${shellQuote(workdir)}`
178
+ );
179
+ if (clone.exitCode !== 0) {
180
+ throw classifyGitFailure(clone, "clone-failed");
181
+ }
182
+ } else {
183
+ reportProgress(onProgress, { phase: "pulling", message: `Updating ${repo} to the latest changes\u2026` });
184
+ const setUrl = await sh(sandbox, `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(authUrl)}`);
185
+ if (setUrl.exitCode !== 0) {
186
+ throw new MaterializeError(`Failed to set git remote: ${setUrl.stderr}`, "pull-failed");
187
+ }
188
+ const pull = await sh(sandbox, `git -C ${shellQuote(workdir)} pull --ff-only`);
189
+ if (pull.exitCode !== 0) {
190
+ throw classifyGitFailure(pull, "pull-failed");
191
+ }
192
+ }
193
+ } finally {
194
+ await scrubRemote(sandbox, workdir, repo, alreadyMaterialized);
195
+ }
196
+ reportProgress(onProgress, { phase: "finalizing", message: "Finalizing workspace\u2026" });
197
+ await storage.markMaterialized({ id: sandboxRow.id });
198
+ }
199
+ async function hasExistingCheckout(sandbox, workdir, repoFullName) {
200
+ const result = await sh(sandbox, `git -C ${shellQuote(workdir)} remote get-url origin`);
201
+ if (result.exitCode !== 0) return false;
202
+ const url = result.stdout.trim().toLowerCase();
203
+ const suffix = `github.com/${repoFullName.toLowerCase()}`;
204
+ return url.endsWith(`${suffix}.git`) || url.endsWith(suffix);
205
+ }
206
+ async function scrubRemote(sandbox, workdir, repoFullName, expectGitDir) {
207
+ const result = await sh(
208
+ sandbox,
209
+ `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(cleanUrl(repoFullName))}`
210
+ );
211
+ if (result.exitCode !== 0 && expectGitDir) {
212
+ throw new MaterializeError(
213
+ `Failed to scrub installation token from git remote: ${result.stderr.trim() || result.stdout.trim()}`,
214
+ "pull-failed"
215
+ );
216
+ }
217
+ }
218
+ function classifyGitFailure(result, fallback) {
219
+ const stderr = result.stderr || "";
220
+ if (/could not resolve host|failed to connect|network is unreachable|Connection timed out/i.test(stderr)) {
221
+ return new MaterializeError(
222
+ "The sandbox could not reach github.com. The sandbox network must allow outbound egress to github.com.",
223
+ "egress-blocked"
224
+ );
225
+ }
226
+ const verb = fallback === "clone-failed" ? "clone" : fallback === "pull-failed" ? "pull" : "push";
227
+ return new MaterializeError(`git ${verb} failed: ${stderr}`, fallback);
228
+ }
229
+ function isValidGitRef(value) {
230
+ return typeof value === "string" && value.length > 0 && value.length <= 255 && // Reject leading-dash refs (e.g. `--mirror`) so the value can never be
231
+ // parsed as a git option when interpolated into a command.
232
+ !value.startsWith("-") && /^[A-Za-z0-9_./-]+$/.test(value);
233
+ }
234
+ function resolveGitIdentity(identity) {
235
+ const login = (identity.login || "").trim();
236
+ const name = (identity.name || "").trim() || login || "Mastra Code";
237
+ const email = (identity.email || "").trim() || (login ? `${login}@users.noreply.github.com` : "mastra-code@users.noreply.github.com");
238
+ return { name, email };
239
+ }
240
+ async function configureGitIdentity(sandbox, workdir, identity) {
241
+ const { name, email } = resolveGitIdentity(identity);
242
+ const setName = await sh(sandbox, `git -C ${shellQuote(workdir)} config user.name ${shellQuote(name)}`);
243
+ if (setName.exitCode !== 0) {
244
+ throw new MaterializeError(`Failed to set git user.name: ${setName.stderr.trim()}`, "commit-failed");
245
+ }
246
+ const setEmail = await sh(sandbox, `git -C ${shellQuote(workdir)} config user.email ${shellQuote(email)}`);
247
+ if (setEmail.exitCode !== 0) {
248
+ throw new MaterializeError(`Failed to set git user.email: ${setEmail.stderr.trim()}`, "commit-failed");
249
+ }
250
+ }
251
+ async function withInstallToken(sandbox, workdir, repoFullName, token, fn) {
252
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repoFullName)) {
253
+ throw new MaterializeError(`Refusing to push: invalid repo full name '${repoFullName}'.`, "push-failed");
254
+ }
255
+ const setUrl = await sh(
256
+ sandbox,
257
+ `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(tokenUrl(repoFullName, token))}`
258
+ );
259
+ if (setUrl.exitCode !== 0) {
260
+ await scrubRemote(sandbox, workdir, repoFullName, false);
261
+ throw new MaterializeError(`Failed to set git remote: ${setUrl.stderr.trim()}`, "push-failed");
262
+ }
263
+ try {
264
+ return await fn();
265
+ } finally {
266
+ await scrubRemote(sandbox, workdir, repoFullName, true);
267
+ }
268
+ }
269
+ async function pushBranch(sandbox, workdir, branch, token, repoFullName) {
270
+ if (!isValidGitRef(branch)) {
271
+ throw new MaterializeError(`Refusing to push: invalid branch name '${branch}'.`, "push-failed");
272
+ }
273
+ await withInstallToken(sandbox, workdir, repoFullName, token, async () => {
274
+ const push = await sh(sandbox, `git -C ${shellQuote(workdir)} push -u origin ${shellQuote(branch)}`);
275
+ if (push.exitCode !== 0) {
276
+ throw classifyGitFailure(push, "push-failed");
277
+ }
278
+ });
279
+ }
280
+ async function commitAll(sandbox, workdir, message, identity) {
281
+ await configureGitIdentity(sandbox, workdir, identity);
282
+ const add = await sh(sandbox, `git -C ${shellQuote(workdir)} add -A`);
283
+ if (add.exitCode !== 0) {
284
+ throw new MaterializeError(`git add failed: ${add.stderr.trim() || add.stdout.trim()}`, "commit-failed");
285
+ }
286
+ const staged = await sh(sandbox, `git -C ${shellQuote(workdir)} diff --cached --quiet`);
287
+ if (staged.exitCode === 0) {
288
+ return { committed: false };
289
+ }
290
+ const commit = await sh(sandbox, `git -C ${shellQuote(workdir)} commit -m ${shellQuote(message)}`);
291
+ if (commit.exitCode !== 0) {
292
+ throw new MaterializeError(`git commit failed: ${commit.stderr.trim() || commit.stdout.trim()}`, "commit-failed");
293
+ }
294
+ return { committed: true };
295
+ }
296
+ var WorktreeError = class extends Error {
297
+ constructor(message, code) {
298
+ super(message);
299
+ this.code = code;
300
+ this.name = "WorktreeError";
301
+ }
302
+ code;
303
+ };
304
+ function safeBranchDir(branch) {
305
+ const sanitized = branch.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/\/+/g, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, 100) || "work";
306
+ if (sanitized === branch) return sanitized;
307
+ const hash = createHash2("sha256").update(branch).digest("hex").slice(0, 8);
308
+ return `${sanitized}-${hash}`;
309
+ }
310
+ function computeWorktreePath(repoWorkdir, branch) {
311
+ const parent = repoWorkdir.replace(/\/+$/, "").split("/").slice(0, -1).join("/") || "";
312
+ return `${parent}/worktrees/${safeBranchDir(branch)}`;
313
+ }
314
+
315
+ // src/integrations/github/subscriptions.ts
316
+ function changeRequestTargetKey(input) {
317
+ return `change-request:${input.installationExternalId}:${input.repositoryExternalId}:${input.changeRequestId}`;
318
+ }
319
+ function sameSession(row, input) {
320
+ return row.orgId === input.orgId && row.sessionId === input.sessionId && row.resourceId === input.resourceId && row.threadId === input.threadId && (row.sessionScope ?? "") === (input.sessionScope ?? "");
321
+ }
322
+ async function subscribeToPullRequest(input, storage) {
323
+ const targetKey = changeRequestTargetKey(input);
324
+ const existing = (await storage.subscriptions.listByTarget(targetKey)).find((row) => sameSession(row, input));
325
+ if (existing) {
326
+ if (existing.status !== "open") await storage.subscriptions.updateStatus(existing.id, "open");
327
+ return { ...existing, status: "open" };
328
+ }
329
+ return storage.subscriptions.create({
330
+ orgId: input.orgId,
331
+ targetKey,
332
+ sessionId: input.sessionId,
333
+ resourceId: input.resourceId,
334
+ threadId: input.threadId,
335
+ sessionScope: input.sessionScope ?? "",
336
+ status: "open",
337
+ data: {
338
+ installationExternalId: input.installationExternalId,
339
+ projectRepositoryId: input.projectRepositoryId,
340
+ repositoryExternalId: input.repositoryExternalId,
341
+ repositorySlug: input.repositorySlug,
342
+ changeRequestId: input.changeRequestId,
343
+ ownerId: input.ownerId,
344
+ source: input.source,
345
+ subscribedByUserId: input.subscribedByUserId ?? null
346
+ }
347
+ });
348
+ }
349
+ async function unsubscribeFromPullRequest(input, storage) {
350
+ const rows = await storage.subscriptions.listByTarget(changeRequestTargetKey(input));
351
+ await Promise.all(rows.filter((row) => sameSession(row, input)).map((row) => storage.subscriptions.delete(row.id)));
352
+ }
353
+ async function listPullRequestSubscriptionsForThread(input, storage) {
354
+ const rows = await storage.subscriptions.listByThread(input.resourceId, input.threadId);
355
+ return rows.filter(
356
+ (row) => row.orgId === input.orgId && row.resourceId === input.resourceId && row.threadId === input.threadId && (row.sessionScope ?? "") === (input.sessionScope ?? "")
357
+ );
358
+ }
359
+ async function listPullRequestSubscriptionsForWebhook(input, options, storage) {
360
+ const rows = await storage.subscriptions.listByTarget(changeRequestTargetKey(input));
361
+ return options?.includeTerminal ? rows : rows.filter((row) => row.status === "open");
362
+ }
363
+ function retirePullRequestSubscription(id, status, storage) {
364
+ return storage.subscriptions.updateStatus(id, status);
365
+ }
366
+
367
+ // src/integrations/github/webhook.ts
368
+ import { createHmac, timingSafeEqual } from "crypto";
369
+ var SUPPORTED_GITHUB_WEBHOOK_EVENTS = /* @__PURE__ */ new Set([
370
+ "issues",
371
+ "issue_comment",
372
+ "pull_request",
373
+ "pull_request_review",
374
+ "pull_request_review_comment"
375
+ ]);
376
+ function normalizeHeader(value) {
377
+ if (!value) return null;
378
+ const trimmed = value.trim();
379
+ return trimmed.length > 0 ? trimmed : null;
380
+ }
381
+ function verifySignature(rawBody, signature, secret) {
382
+ if (!signature.startsWith("sha256=")) return false;
383
+ const signatureHex = signature.slice("sha256=".length);
384
+ if (!/^[a-fA-F0-9]{64}$/.test(signatureHex)) return false;
385
+ const expectedHex = createHmac("sha256", secret).update(rawBody).digest("hex");
386
+ const received = Buffer.from(signatureHex, "hex");
387
+ const expected = Buffer.from(expectedHex, "hex");
388
+ return received.length === expected.length && timingSafeEqual(received, expected);
389
+ }
390
+ async function parseGithubWebhook(c, secret) {
391
+ if (!secret) {
392
+ return { status: 401, body: { error: "unauthorized", message: "GitHub webhook secret is not configured" } };
393
+ }
394
+ const event = normalizeHeader(c.req.header("x-github-event"));
395
+ const deliveryId = normalizeHeader(c.req.header("x-github-delivery"));
396
+ const signature = normalizeHeader(c.req.header("x-hub-signature-256"));
397
+ if (!event) return { status: 400, body: { error: "bad_request", message: "Missing x-github-event header" } };
398
+ if (!deliveryId) return { status: 400, body: { error: "bad_request", message: "Missing x-github-delivery header" } };
399
+ if (!signature)
400
+ return { status: 401, body: { error: "unauthorized", message: "Missing x-hub-signature-256 header" } };
401
+ const rawBody = await c.req.text();
402
+ if (!verifySignature(rawBody, signature, secret)) {
403
+ return { status: 401, body: { error: "unauthorized", message: "Invalid GitHub webhook signature" } };
404
+ }
405
+ let payload;
406
+ try {
407
+ payload = JSON.parse(rawBody);
408
+ } catch {
409
+ return { status: 400, body: { error: "bad_request", message: "Malformed JSON payload" } };
410
+ }
411
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
412
+ return { status: 400, body: { error: "bad_request", message: "Payload must be a JSON object" } };
413
+ }
414
+ return { event, deliveryId, payload };
415
+ }
416
+ function getObject(value) {
417
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
418
+ }
419
+ function getString(value) {
420
+ return typeof value === "string" && value.length > 0 ? value : void 0;
421
+ }
422
+ function getNumber(value) {
423
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
424
+ }
425
+ function getBoolean(value) {
426
+ return typeof value === "boolean" ? value : void 0;
427
+ }
428
+ function getLabels(value) {
429
+ if (!Array.isArray(value)) return [];
430
+ return value.map((label) => typeof label === "string" ? label : getString(getObject(label)?.name)).filter((label) => Boolean(label));
431
+ }
432
+ function getIssueTriageRunInput(parsed) {
433
+ if (parsed.event !== "issues" || getString(parsed.payload.action) !== "opened") return null;
434
+ const repository = getString(getObject(parsed.payload.repository)?.full_name);
435
+ const issue = getObject(parsed.payload.issue);
436
+ const sender = getString(getObject(parsed.payload.sender)?.login);
437
+ const installationId = getNumber(getObject(parsed.payload.installation)?.id);
438
+ const issueNumber = getNumber(issue?.number);
439
+ const issueTitle = getString(issue?.title);
440
+ const issueUrl = getString(issue?.html_url);
441
+ if (!repository || !installationId || !issueNumber || !issueTitle || !issueUrl) return null;
442
+ return {
443
+ repository,
444
+ issueNumber,
445
+ issueTitle,
446
+ issueUrl,
447
+ labels: getLabels(issue?.labels),
448
+ sender,
449
+ installationId
450
+ };
451
+ }
452
+ function normalizeGithubWebhookMetadata(parsed) {
453
+ const { event, deliveryId, payload } = parsed;
454
+ const repository = getObject(payload.repository);
455
+ const issue = getObject(payload.issue);
456
+ const pullRequest = getObject(payload.pull_request);
457
+ const sender = getObject(payload.sender);
458
+ const installation = getObject(payload.installation);
459
+ const issuePullRequest = getObject(issue?.pull_request);
460
+ return {
461
+ event,
462
+ action: getString(payload.action),
463
+ deliveryId,
464
+ repository: getString(repository?.full_name),
465
+ repositoryId: getNumber(repository?.id),
466
+ issueNumber: getNumber(issue?.number),
467
+ pullRequestNumber: getNumber(pullRequest?.number) ?? (event === "issue_comment" && issuePullRequest ? getNumber(issue?.number) : void 0),
468
+ sender: getString(sender?.login),
469
+ senderType: getString(sender?.type),
470
+ installationId: getNumber(installation?.id)
471
+ };
472
+ }
473
+ function notificationSummary(metadata, label) {
474
+ const actor = metadata.sender ? `${metadata.sender} ` : "";
475
+ return `${actor}${label} on ${metadata.repository}#${metadata.pullRequestNumber}`;
476
+ }
477
+ function notificationTargetUrl(event, payload) {
478
+ if (event === "issue_comment" || event === "pull_request_review_comment") {
479
+ return getString(getObject(payload.comment)?.html_url);
480
+ }
481
+ if (event === "pull_request_review") {
482
+ return getString(getObject(payload.review)?.html_url);
483
+ }
484
+ return getString(getObject(payload.pull_request)?.html_url);
485
+ }
486
+ function classifyGithubWebhook(parsed) {
487
+ const metadata = normalizeGithubWebhookMetadata(parsed);
488
+ const { event, payload } = parsed;
489
+ const action = metadata.action;
490
+ if (!action || !metadata.repositoryId || !metadata.installationId || !metadata.pullRequestNumber || !metadata.repository) {
491
+ return void 0;
492
+ }
493
+ let priority;
494
+ let kind;
495
+ let label;
496
+ let terminal = false;
497
+ if (event === "pull_request_review" && action === "submitted") {
498
+ const state = getString(getObject(payload.review)?.state)?.toLowerCase().replaceAll("_", "-");
499
+ priority = state === "approved" || state === "changes-requested" ? "urgent" : "high";
500
+ kind = state === "approved" ? "review-approved" : state === "changes-requested" ? "review-changes-requested" : "review-submitted";
501
+ label = state === "approved" ? "approved the pull request" : state === "changes-requested" ? "requested changes" : "submitted a review";
502
+ } else if (event === "pull_request" && action === "closed") {
503
+ const merged = getBoolean(getObject(payload.pull_request)?.merged) === true;
504
+ priority = "urgent";
505
+ kind = merged ? "pull-request-merged" : "pull-request-closed";
506
+ label = merged ? "merged the pull request" : "closed the pull request";
507
+ terminal = true;
508
+ } else if (event === "issue_comment" && action === "created") {
509
+ priority = "high";
510
+ kind = "issue-comment-created";
511
+ label = "commented";
512
+ } else if (event === "pull_request_review_comment" && action === "created") {
513
+ priority = "high";
514
+ kind = "review-comment-created";
515
+ label = "left a review comment";
516
+ } else if (event === "pull_request" && action === "reopened") {
517
+ priority = "high";
518
+ kind = "pull-request-reopened";
519
+ label = "reopened the pull request";
520
+ } else if (event === "pull_request_review" && action === "dismissed") {
521
+ priority = "high";
522
+ kind = "review-dismissed";
523
+ label = "dismissed a review";
524
+ } else if (event === "pull_request" && [
525
+ "synchronize",
526
+ "ready_for_review",
527
+ "converted_to_draft",
528
+ "assigned",
529
+ "unassigned",
530
+ "review_requested",
531
+ "review_request_removed"
532
+ ].includes(action)) {
533
+ priority = "medium";
534
+ kind = `pull-request-${action.replaceAll("_", "-")}`;
535
+ label = action.replaceAll("_", " ");
536
+ } else if (event === "pull_request" && ["edited", "labeled", "unlabeled", "milestoned", "demilestoned"].includes(action)) {
537
+ priority = "low";
538
+ kind = `pull-request-${action.replaceAll("_", "-")}`;
539
+ label = action.replaceAll("_", " ");
540
+ } else {
541
+ return void 0;
542
+ }
543
+ return {
544
+ action,
545
+ kind,
546
+ priority,
547
+ summary: notificationSummary(metadata, label),
548
+ terminal,
549
+ metadata: {
550
+ ...metadata,
551
+ pullRequestNumber: metadata.pullRequestNumber,
552
+ repositoryId: metadata.repositoryId,
553
+ installationId: metadata.installationId
554
+ },
555
+ payload
556
+ };
557
+ }
558
+ async function resolveSubscriptionSession(controller, subscription) {
559
+ const { sessionId, resourceId, threadId } = subscription;
560
+ if (!sessionId || !resourceId || !threadId) {
561
+ throw new Error(`GitHub subscription ${subscription.id} is missing its session binding.`);
562
+ }
563
+ const scope = subscription.sessionScope || void 0;
564
+ let session = await controller.getSessionByResource(resourceId, scope);
565
+ if (!session) {
566
+ const tags = {
567
+ factoryProjectId: resourceId,
568
+ projectRepositoryId: subscription.data.projectRepositoryId,
569
+ ...scope ? { worktreePath: scope } : {}
570
+ };
571
+ session = await controller.createSession({
572
+ id: sessionId,
573
+ ownerId: subscription.data.ownerId,
574
+ resourceId,
575
+ scope,
576
+ tags
577
+ });
578
+ }
579
+ if (session.thread.getId() !== threadId) {
580
+ await session.thread.switch({ threadId, emitEvent: false });
581
+ }
582
+ if (session.thread.getId() !== threadId) {
583
+ throw new Error(`Session ${sessionId} did not bind thread ${threadId}.`);
584
+ }
585
+ return session;
586
+ }
587
+ var AUTHORIZED_BOTS = /* @__PURE__ */ new Set(["coderabbitai[bot]", "devin-ai-integration[bot]"]);
588
+ var AUTHORIZED_PERMISSIONS = /* @__PURE__ */ new Set(["admin", "maintain", "write"]);
589
+ var PERMISSION_CHECK_TIMEOUT_MS = 5e3;
590
+ var AUTHOR_GATED_KINDS = /* @__PURE__ */ new Set([
591
+ "issue-comment-created",
592
+ "review-comment-created",
593
+ "review-submitted",
594
+ "review-approved",
595
+ "review-changes-requested",
596
+ "review-dismissed"
597
+ ]);
598
+ async function isAuthorizedGithubSender(notification, github) {
599
+ if (!AUTHOR_GATED_KINDS.has(notification.kind)) return true;
600
+ const sender = notification.metadata.sender;
601
+ const repository = notification.metadata.repository;
602
+ if (!sender || !repository) return false;
603
+ const normalizedSender = sender.toLowerCase();
604
+ if (notification.metadata.senderType?.toLowerCase() === "bot" || normalizedSender.endsWith("[bot]")) {
605
+ return AUTHORIZED_BOTS.has(normalizedSender);
606
+ }
607
+ if (!github) return false;
608
+ const abortController = new AbortController();
609
+ let timeout;
610
+ try {
611
+ const permission = await Promise.race([
612
+ github.getRepositoryCollaboratorPermission(
613
+ notification.metadata.installationId,
614
+ repository,
615
+ sender,
616
+ abortController.signal
617
+ ),
618
+ new Promise((resolve) => {
619
+ timeout = setTimeout(() => {
620
+ abortController.abort();
621
+ resolve(void 0);
622
+ }, PERMISSION_CHECK_TIMEOUT_MS);
623
+ })
624
+ ]);
625
+ return permission !== void 0 && AUTHORIZED_PERMISSIONS.has(permission);
626
+ } catch {
627
+ return false;
628
+ } finally {
629
+ if (timeout) clearTimeout(timeout);
630
+ }
631
+ }
632
+ async function dispatchGithubWebhook(parsed, dependencies) {
633
+ const notification = classifyGithubWebhook(parsed);
634
+ if (!notification) return { delivered: 0, failed: 0, ignored: true };
635
+ const isAuthorizedSender = dependencies.isAuthorizedSender ?? ((n) => isAuthorizedGithubSender(n, dependencies.github));
636
+ if (!await isAuthorizedSender(notification)) {
637
+ return { delivered: 0, failed: 0, ignored: true };
638
+ }
639
+ const target = {
640
+ installationExternalId: notification.metadata.installationId.toString(),
641
+ repositoryExternalId: notification.metadata.repositoryId.toString(),
642
+ changeRequestId: notification.metadata.pullRequestNumber.toString()
643
+ };
644
+ const listSubscriptions = dependencies.listSubscriptions ?? ((subscriptionTarget, options) => {
645
+ if (!dependencies.github) throw new Error("GitHub integration is required to load webhook subscriptions.");
646
+ return listPullRequestSubscriptionsForWebhook(
647
+ subscriptionTarget,
648
+ options,
649
+ dependencies.github.integrationStorage
650
+ );
651
+ });
652
+ const retireSubscription = dependencies.retireSubscription ?? ((id, status) => {
653
+ if (!dependencies.github) throw new Error("GitHub integration is required to retire webhook subscriptions.");
654
+ return retirePullRequestSubscription(id, status, dependencies.github.integrationStorage);
655
+ });
656
+ const subscriptions = await listSubscriptions(target, { includeTerminal: notification.action === "reopened" });
657
+ let delivered = 0;
658
+ let failed = 0;
659
+ for (const subscription of subscriptions) {
660
+ try {
661
+ const session = await resolveSubscriptionSession(dependencies.controller, subscription);
662
+ const result = await session.sendNotificationSignal({
663
+ source: "github",
664
+ kind: notification.kind,
665
+ summary: notification.summary,
666
+ priority: notification.priority,
667
+ payload: notification.payload,
668
+ sourceId: parsed.deliveryId,
669
+ dedupeKey: `${parsed.deliveryId}:${subscription.sessionId}:${subscription.threadId}`,
670
+ coalesceKey: `github:${subscription.data.repositoryExternalId}:pull-request:${subscription.data.changeRequestId}`,
671
+ metadata: {
672
+ event: notification.metadata.event,
673
+ action: notification.action,
674
+ repository: notification.metadata.repository,
675
+ issueNumber: notification.metadata.issueNumber,
676
+ pullRequestNumber: notification.metadata.pullRequestNumber,
677
+ targetUrl: notificationTargetUrl(parsed.event, parsed.payload),
678
+ deliveryId: parsed.deliveryId
679
+ }
680
+ });
681
+ await Promise.all([result.persisted, result.accepted].filter(Boolean));
682
+ if (notification.terminal) {
683
+ await retireSubscription(subscription.id, notification.kind === "pull-request-merged" ? "merged" : "closed");
684
+ } else if (notification.action === "reopened") {
685
+ await retireSubscription(subscription.id, "open");
686
+ }
687
+ delivered += 1;
688
+ } catch (error) {
689
+ failed += 1;
690
+ dependencies.onTargetError?.(subscription, error);
691
+ }
692
+ }
693
+ return { delivered, failed, ignored: false };
694
+ }
695
+ async function handleGithubWebhook(c, options) {
696
+ const parsed = await parseGithubWebhook(c, options.github.webhookSecret);
697
+ if ("status" in parsed) return parsed;
698
+ if (!SUPPORTED_GITHUB_WEBHOOK_EVENTS.has(parsed.event)) {
699
+ return { status: 202, body: { ok: true, ignored: true } };
700
+ }
701
+ const metadata = normalizeGithubWebhookMetadata(parsed);
702
+ console.info("[GitHub Webhook]", metadata);
703
+ if (options.ingestFactoryEvent) {
704
+ await options.ingestFactoryEvent(parsed);
705
+ } else {
706
+ const issueTriageRun = getIssueTriageRunInput(parsed);
707
+ if (issueTriageRun && options.runIssueTriage) {
708
+ void options.runIssueTriage(issueTriageRun).catch((error) => {
709
+ console.error("[GitHub Webhook] Failed to run issue triage", {
710
+ deliveryId: metadata.deliveryId,
711
+ repository: metadata.repository,
712
+ issueNumber: metadata.issueNumber,
713
+ error: error instanceof Error ? error.message : String(error)
714
+ });
715
+ });
716
+ }
717
+ }
718
+ if (!options.controller) {
719
+ return { status: 202, body: { ok: true } };
720
+ }
721
+ const result = await dispatchGithubWebhook(parsed, options);
722
+ if (result.failed > 0) {
723
+ console.warn(`[GitHub Webhook] ${result.failed} subscribed target(s) failed for delivery ${parsed.deliveryId}.`);
724
+ }
725
+ return { status: 202, body: { ok: true, ...result.ignored ? { ignored: true } : {} } };
726
+ }
727
+
728
+ // src/integrations/github/routes.ts
729
+ function loose(c) {
730
+ return c;
731
+ }
732
+ async function resolveFactoryDefaultModelId(projects, factoryProjectId) {
733
+ if (!projects || !factoryProjectId) return void 0;
734
+ try {
735
+ const project = await projects.getById({ id: factoryProjectId });
736
+ return project?.defaultModelId ?? void 0;
737
+ } catch {
738
+ return void 0;
739
+ }
740
+ }
741
+ function pullRequestNumberFromUrl(value, expectedRepo) {
742
+ try {
743
+ const url = new URL(value);
744
+ const match = url.pathname.match(/^\/([^/]+\/[^/]+)\/pull\/(\d+)\/?$/);
745
+ if (url.protocol !== "https:" || url.hostname !== "github.com" || match?.[1]?.toLowerCase() !== expectedRepo.toLowerCase()) {
746
+ return void 0;
747
+ }
748
+ const number = Number(match[2]);
749
+ return Number.isInteger(number) && number > 0 ? number : void 0;
750
+ } catch {
751
+ return void 0;
752
+ }
753
+ }
754
+ function isCanonicalGithubIssueUrl(value, repoFullName, issueNumber) {
755
+ try {
756
+ const url = new URL(value);
757
+ const [owner, repo] = repoFullName.split("/");
758
+ return url.protocol === "https:" && url.hostname === "github.com" && url.pathname === `/${owner}/${repo}/issues/${issueNumber}` && url.search === "" && url.hash === "";
759
+ } catch {
760
+ return false;
761
+ }
762
+ }
763
+ function isValidGitRef2(value) {
764
+ return typeof value === "string" && value.length > 0 && value.length <= 255 && /^[A-Za-z0-9_./-]+$/.test(value);
765
+ }
766
+ async function resolveOrgTenant(c, auth) {
767
+ await auth.ensureUser(c);
768
+ const tenant = auth.tenant(c);
769
+ if (!tenant) return { response: c.json({ error: "unauthorized" }, 401) };
770
+ if (!tenant.orgId) {
771
+ return {
772
+ response: c.json(
773
+ {
774
+ error: "organization_required",
775
+ message: "GitHub projects require a WorkOS organization. Personal accounts cannot connect repositories."
776
+ },
777
+ 403
778
+ )
779
+ };
780
+ }
781
+ return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };
782
+ }
783
+ function parseListPage(raw) {
784
+ if (raw === void 0) return 1;
785
+ if (!/^\d{1,5}$/.test(raw)) return null;
786
+ const page = Number(raw);
787
+ return page >= 1 ? page : null;
788
+ }
789
+ var VALID_ISSUE_LABEL_FILTERS = /* @__PURE__ */ new Set(["auto-triaged", "needs-approval"]);
790
+ function parseIssueLabelFilter(raw) {
791
+ if (raw === void 0 || raw === "") return void 0;
792
+ if (VALID_ISSUE_LABEL_FILTERS.has(raw)) return raw;
793
+ return null;
794
+ }
795
+ function parseIssueNumberParam(raw) {
796
+ if (!raw || !/^\d{1,10}$/.test(raw)) return null;
797
+ const issueNumber = Number(raw);
798
+ return Number.isSafeInteger(issueNumber) && issueNumber > 0 ? issueNumber : null;
799
+ }
800
+ function parseStringList(value) {
801
+ if (!Array.isArray(value)) return [];
802
+ return value.filter((item) => typeof item === "string" && item.length > 0);
803
+ }
804
+ async function resolveProjectRepository(args) {
805
+ const projectRepository = await args.github.sourceControlStorage.projectRepositories.get({
806
+ orgId: args.orgId,
807
+ id: args.projectRepositoryId
808
+ });
809
+ if (!projectRepository) return null;
810
+ const connection = await args.github.sourceControlStorage.connections.get({
811
+ orgId: args.orgId,
812
+ id: projectRepository.connectionId
813
+ });
814
+ if (!connection) return null;
815
+ const repository = await args.github.sourceControlStorage.repositories.get({
816
+ orgId: args.orgId,
817
+ id: projectRepository.repositoryId
818
+ });
819
+ if (!repository) return null;
820
+ const installation = await args.github.sourceControlStorage.installations.get({
821
+ orgId: args.orgId,
822
+ id: connection.installationId
823
+ });
824
+ if (!installation) return null;
825
+ return {
826
+ ...projectRepository,
827
+ connection,
828
+ installation,
829
+ repository,
830
+ factoryProjectId: connection.factoryProjectId,
831
+ defaultBranch: projectRepository.branch ?? repository.defaultBranch
832
+ };
833
+ }
834
+ function polledIssueEvent(project, issue) {
835
+ const repositoryId = Number(project.repository.externalId);
836
+ return {
837
+ event: "issues",
838
+ deliveryId: `poll:${repositoryId}:issue:${issue.number}:${issue.createdAt}`,
839
+ payload: {
840
+ action: "opened",
841
+ installation: { id: Number(project.installation.externalId) },
842
+ repository: { id: repositoryId, full_name: project.repository.slug },
843
+ sender: { login: issue.author ?? "__unknown__" },
844
+ issue: {
845
+ number: issue.number,
846
+ title: issue.title,
847
+ html_url: issue.url,
848
+ created_at: issue.createdAt,
849
+ labels: issue.labels.map((name) => ({ name }))
850
+ }
851
+ }
852
+ };
853
+ }
854
+ function polledPullRequestEvent(project, pullRequest) {
855
+ const repositoryId = Number(project.repository.externalId);
856
+ return {
857
+ event: "pull_request",
858
+ deliveryId: `poll:${repositoryId}:pull-request:${pullRequest.number}:${pullRequest.createdAt}`,
859
+ payload: {
860
+ action: "opened",
861
+ installation: { id: Number(project.installation.externalId) },
862
+ repository: { id: repositoryId, full_name: project.repository.slug },
863
+ sender: { login: pullRequest.author ?? "__unknown__" },
864
+ pull_request: {
865
+ number: pullRequest.number,
866
+ title: pullRequest.title,
867
+ html_url: pullRequest.url,
868
+ created_at: pullRequest.createdAt,
869
+ state: "open",
870
+ merged: false,
871
+ head: { ref: pullRequest.headBranch },
872
+ base: { ref: pullRequest.baseBranch }
873
+ }
874
+ }
875
+ };
876
+ }
877
+ async function ingestPolledEvents(events, ingestFactoryEvent) {
878
+ if (!ingestFactoryEvent) return;
879
+ const results = await Promise.allSettled(events.map((event) => ingestFactoryEvent(event)));
880
+ const rejected = results.find((result) => result.status === "rejected");
881
+ if (rejected) throw rejected.reason;
882
+ }
883
+ function buildGithubRoutes(options) {
884
+ const routes = [];
885
+ const { auth, fleet, storage, github, stateSigner, emitAudit } = options;
886
+ const diagnostics = () => getGithubFeatureDiagnostics({ github, auth, appDbConfigured: storage !== void 0, stateSigner, fleet });
887
+ routes.push(
888
+ registerApiRoute("/web/github/status", {
889
+ method: "GET",
890
+ requiresAuth: false,
891
+ handler: async (c) => {
892
+ if (!isGithubFeatureEnabled({ github, auth }) || !github || !stateSigner) {
893
+ return c.json({
894
+ enabled: false,
895
+ connected: false,
896
+ installations: [],
897
+ reason: "missing_config",
898
+ diagnostics: diagnostics()
899
+ });
900
+ }
901
+ await auth.ensureUser(loose(c));
902
+ const tenant = auth.tenant(loose(c));
903
+ if (!tenant) return c.json({ error: "unauthorized", reason: "auth_required" }, 401);
904
+ if (!tenant.orgId) {
905
+ return c.json({
906
+ enabled: true,
907
+ sandboxEnabled: fleet.enabled,
908
+ organizationRequired: true,
909
+ connected: false,
910
+ installations: [],
911
+ reason: "organization_required",
912
+ diagnostics: diagnostics()
913
+ });
914
+ }
915
+ const rows = options.github ? await options.github.sourceControlStorage.installations.list({ orgId: tenant.orgId }) : [];
916
+ const connected = rows.length > 0;
917
+ return c.json({
918
+ enabled: true,
919
+ sandboxEnabled: fleet.enabled,
920
+ connected,
921
+ installations: rows.map((r) => ({
922
+ installationId: Number(r.externalId),
923
+ accountLogin: r.accountName,
924
+ accountType: r.accountType
925
+ })),
926
+ reason: connected ? "ready" : "not_connected",
927
+ diagnostics: diagnostics()
928
+ });
929
+ }
930
+ })
931
+ );
932
+ if (!isGithubFeatureEnabled({ github, auth }) || !github || !stateSigner) {
933
+ return routes;
934
+ }
935
+ const signState = (orgId, userId) => stateSigner.sign(orgId, userId);
936
+ const verifyState = (state) => stateSigner.verify(state);
937
+ const { runIssueTriage } = options;
938
+ const runBoardIssueTriage = runIssueTriage ? async (input) => {
939
+ if (!input.resourceId || !input.projectPath) {
940
+ throw new Error("GitHub issue triage requires an explicit Factory project repository");
941
+ }
942
+ await github.addIssueLabels(input.installationId, input.repository, input.issueNumber, ["auto-triaged"]);
943
+ return runIssueTriage({
944
+ ...input,
945
+ defaultModelId: input.defaultModelId ?? await resolveFactoryDefaultModelId(options.projects, input.resourceId),
946
+ labels: input.labels.includes("auto-triaged") ? input.labels : [...input.labels, "auto-triaged"]
947
+ });
948
+ } : void 0;
949
+ routes.push(
950
+ registerApiRoute("/web/github/subscriptions", {
951
+ method: "GET",
952
+ handler: async (c) => {
953
+ await auth.ensureUser(loose(c));
954
+ const tenant = auth.tenant(loose(c));
955
+ if (!tenant?.orgId) return c.json({ error: "unauthorized" }, 401);
956
+ const resourceId = c.req.query("resourceId");
957
+ const threadId = c.req.query("threadId");
958
+ const sessionScope = c.req.query("scope");
959
+ if (!resourceId || !threadId) return c.json({ error: "resourceId and threadId are required" }, 400);
960
+ const subscriptions = await listPullRequestSubscriptionsForThread(
961
+ {
962
+ orgId: tenant.orgId,
963
+ resourceId,
964
+ threadId,
965
+ sessionScope
966
+ },
967
+ github.integrationStorage
968
+ );
969
+ return c.json({
970
+ subscriptions: subscriptions.map((subscription) => ({
971
+ id: subscription.id,
972
+ repoFullName: subscription.data.repositorySlug,
973
+ pullRequestNumber: Number(subscription.data.changeRequestId),
974
+ status: subscription.status,
975
+ url: `https://github.com/${subscription.data.repositorySlug}/pull/${subscription.data.changeRequestId}`
976
+ }))
977
+ });
978
+ }
979
+ }),
980
+ registerApiRoute("/web/github/webhook", {
981
+ method: "POST",
982
+ requiresAuth: false,
983
+ handler: async (c) => {
984
+ const result = await handleGithubWebhook(loose(c), {
985
+ github,
986
+ runIssueTriage: runBoardIssueTriage,
987
+ ingestFactoryEvent: options.ingestFactoryEvent,
988
+ ...options.controller ? {
989
+ controller: options.controller,
990
+ onTargetError: (subscription, error) => {
991
+ console.warn(
992
+ `[GitHub Webhook] Delivery failed for subscription ${subscription.id} (${subscription.resourceId}/${subscription.threadId}).`,
993
+ error
994
+ );
995
+ }
996
+ } : {}
997
+ });
998
+ return c.json(result.body, result.status);
999
+ }
1000
+ })
1001
+ );
1002
+ const redirectUri = options.redirectUri ?? `${(options.baseUrl ?? "").replace(/\/$/, "")}/auth/github/callback`;
1003
+ routes.push(
1004
+ registerApiRoute("/auth/github/connect", {
1005
+ method: "GET",
1006
+ requiresAuth: false,
1007
+ handler: async (c) => {
1008
+ const resolved = await resolveOrgTenant(loose(c), auth);
1009
+ if ("response" in resolved) return resolved.response;
1010
+ const state = signState(resolved.tenant.orgId, resolved.tenant.userId);
1011
+ if (c.req.query("manage")) return c.redirect(github.buildInstallUrl(state));
1012
+ return c.redirect(github.buildOAuthIdentifyUrl(state, redirectUri));
1013
+ }
1014
+ })
1015
+ );
1016
+ routes.push(
1017
+ registerApiRoute("/auth/github/callback", {
1018
+ method: "GET",
1019
+ requiresAuth: false,
1020
+ handler: async (c) => {
1021
+ const resolved = await resolveOrgTenant(loose(c), auth);
1022
+ if ("response" in resolved) return resolved.response;
1023
+ const { orgId, userId } = resolved.tenant;
1024
+ const state = c.req.query("state");
1025
+ if (!state) {
1026
+ return c.redirect(github.buildOAuthIdentifyUrl(signState(orgId, userId), redirectUri));
1027
+ }
1028
+ const stateTenant = verifyState(state);
1029
+ if (!stateTenant || stateTenant.userId !== userId || stateTenant.orgId !== orgId) {
1030
+ console.warn(
1031
+ "[GitHub] Install callback rejected: state/tenant mismatch.",
1032
+ JSON.stringify({
1033
+ stateValid: Boolean(stateTenant),
1034
+ stateOrgId: stateTenant?.orgId,
1035
+ stateUserId: stateTenant?.userId,
1036
+ sessionOrgId: orgId,
1037
+ sessionUserId: userId
1038
+ })
1039
+ );
1040
+ return c.redirect("/?github=error");
1041
+ }
1042
+ const code = c.req.query("code");
1043
+ if (!code) {
1044
+ return c.redirect(github.buildOAuthIdentifyUrl(signState(orgId, userId), redirectUri));
1045
+ }
1046
+ try {
1047
+ const userToken = await github.exchangeOAuthCode(code, redirectUri);
1048
+ const installations = await github.listUserInstallations(userToken);
1049
+ if (installations.length === 0) {
1050
+ return c.redirect(github.buildInstallUrl(signState(orgId, userId)));
1051
+ }
1052
+ for (const inst of installations) {
1053
+ await github.sourceControlStorage.installations.upsert({
1054
+ orgId,
1055
+ connectedByUserId: userId,
1056
+ externalId: inst.installationId.toString(),
1057
+ accountName: inst.accountLogin,
1058
+ accountType: inst.accountType
1059
+ });
1060
+ }
1061
+ } catch (error) {
1062
+ console.warn(
1063
+ `[GitHub] Install callback failed to persist installations for org ${orgId} / user ${userId}.`,
1064
+ error
1065
+ );
1066
+ return c.redirect("/?github=error");
1067
+ }
1068
+ return c.redirect("/?github=connected");
1069
+ }
1070
+ })
1071
+ );
1072
+ routes.push(
1073
+ registerApiRoute("/web/github/repos", {
1074
+ method: "GET",
1075
+ requiresAuth: false,
1076
+ handler: async (c) => {
1077
+ const resolved = await resolveOrgTenant(loose(c), auth);
1078
+ if ("response" in resolved) return resolved.response;
1079
+ const installs = await github.sourceControlStorage.installations.list({ orgId: resolved.tenant.orgId });
1080
+ const query = (c.req.query("q") ?? "").toLowerCase();
1081
+ const repos = [];
1082
+ const seenRepositoryIds = /* @__PURE__ */ new Set();
1083
+ for (const inst of installs) {
1084
+ let list;
1085
+ try {
1086
+ list = await github.listInstallationRepos(Number(inst.externalId));
1087
+ } catch (err) {
1088
+ if (err.status !== 404) throw err;
1089
+ console.error(`[MastraCode Web] pruning stale GitHub installation ${inst.externalId} (404 from GitHub)`);
1090
+ await github.sourceControlStorage.installations.delete({ orgId: resolved.tenant.orgId, id: inst.id });
1091
+ continue;
1092
+ }
1093
+ for (const repo of list) {
1094
+ if (query && !repo.fullName.toLowerCase().includes(query)) continue;
1095
+ if (seenRepositoryIds.has(repo.id)) continue;
1096
+ seenRepositoryIds.add(repo.id);
1097
+ const repository = await github.sourceControlStorage.repositories.upsert({
1098
+ orgId: resolved.tenant.orgId,
1099
+ input: {
1100
+ installationId: inst.id,
1101
+ externalId: repo.id.toString(),
1102
+ slug: repo.fullName,
1103
+ defaultBranch: isValidGitRef2(repo.defaultBranch) ? repo.defaultBranch : "main",
1104
+ providerMetadata: { private: repo.private, owner: repo.owner }
1105
+ }
1106
+ });
1107
+ repos.push({
1108
+ ...repo,
1109
+ installationStorageId: inst.id,
1110
+ repositoryStorageId: repository.id,
1111
+ sandboxProvider: fleet.provider,
1112
+ sandboxWorkdir: fleet.computeWorkdir(repo.fullName)
1113
+ });
1114
+ }
1115
+ }
1116
+ return c.json({ repos });
1117
+ }
1118
+ })
1119
+ );
1120
+ routes.push(
1121
+ registerApiRoute("/web/github/projects/:id/ensure", {
1122
+ method: "POST",
1123
+ requiresAuth: false,
1124
+ handler: async (c) => {
1125
+ const resolved = await resolveOrgTenant(loose(c), auth);
1126
+ if ("response" in resolved) return resolved.response;
1127
+ const { orgId, userId } = resolved.tenant;
1128
+ if (!fleet.enabled) {
1129
+ return c.json({ error: "sandbox_not_configured", message: "No sandbox provider is configured." }, 503);
1130
+ }
1131
+ const projectRepositoryId = c.req.param("id");
1132
+ if (!projectRepositoryId) return c.json({ error: "Project repository not found" }, 404);
1133
+ const project = await resolveProjectRepository({ github, orgId, projectRepositoryId });
1134
+ if (!project) {
1135
+ return c.json({ error: "Project repository not found" }, 404);
1136
+ }
1137
+ const wantsStream = (c.req.header("accept") ?? "").includes("text/event-stream");
1138
+ if (wantsStream) {
1139
+ return streamSSE(loose(c), async (stream) => {
1140
+ try {
1141
+ const result = await prepareProject({
1142
+ github,
1143
+ fleet,
1144
+ project,
1145
+ userId,
1146
+ onProgress: (ev) => void stream.writeSSE({ event: "progress", data: JSON.stringify(ev) })
1147
+ });
1148
+ await stream.writeSSE({ event: "done", data: JSON.stringify(result) });
1149
+ } catch (err) {
1150
+ await stream.writeSSE({ event: "error", data: JSON.stringify(ensureErrorPayload(err).body) });
1151
+ }
1152
+ });
1153
+ }
1154
+ try {
1155
+ const result = await prepareProject({ github, fleet, project, userId });
1156
+ return c.json(result);
1157
+ } catch (err) {
1158
+ const { status, body } = ensureErrorPayload(err);
1159
+ return c.json(body, status);
1160
+ }
1161
+ }
1162
+ })
1163
+ );
1164
+ routes.push(
1165
+ registerApiRoute("/web/github/projects/:id/issues", {
1166
+ method: "GET",
1167
+ requiresAuth: false,
1168
+ handler: async (c) => {
1169
+ const loaded = await loadOrgProject({ github, auth, c: loose(c) });
1170
+ if ("response" in loaded) return loaded.response;
1171
+ const page = parseListPage(c.req.query("page"));
1172
+ if (page === null) return c.json({ error: "invalid_page" }, 400);
1173
+ const label = parseIssueLabelFilter(c.req.query("label"));
1174
+ if (label === null) return c.json({ error: "invalid_label" }, 400);
1175
+ try {
1176
+ const { issues, nextCursor } = await github.intake.listIssues({
1177
+ connection: {
1178
+ type: "app-installation",
1179
+ installationId: Number(loaded.project.installation.externalId)
1180
+ },
1181
+ sourceIds: [loaded.project.repository.slug],
1182
+ labels: label ? [label] : void 0,
1183
+ cursor: String(page)
1184
+ });
1185
+ const responseIssues = issues.map((issue) => ({
1186
+ number: Number(issue.id),
1187
+ title: issue.title,
1188
+ url: issue.url,
1189
+ author: issue.author,
1190
+ labels: issue.labels,
1191
+ comments: issue.commentCount ?? 0,
1192
+ createdAt: issue.createdAt,
1193
+ updatedAt: issue.updatedAt
1194
+ }));
1195
+ await ingestPolledEvents(
1196
+ responseIssues.map((issue) => polledIssueEvent(loaded.project, issue)),
1197
+ options.ingestFactoryEvent
1198
+ );
1199
+ return c.json({
1200
+ issues: responseIssues,
1201
+ nextPage: nextCursor === null ? null : Number(nextCursor)
1202
+ });
1203
+ } catch (err) {
1204
+ return c.json(
1205
+ { error: "github_fetch_failed", message: err instanceof Error ? err.message : String(err) },
1206
+ 502
1207
+ );
1208
+ }
1209
+ }
1210
+ })
1211
+ );
1212
+ routes.push(
1213
+ registerApiRoute("/web/github/projects/:id/issues/:number/triage", {
1214
+ method: "POST",
1215
+ requiresAuth: false,
1216
+ handler: async (c) => {
1217
+ const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
1218
+ if ("response" in owned) return owned.response;
1219
+ const { project, sandboxRow } = owned;
1220
+ const issueNumber = parseIssueNumberParam(c.req.param("number"));
1221
+ if (issueNumber === null) return c.json({ error: "invalid_issue_number" }, 400);
1222
+ let body;
1223
+ try {
1224
+ body = await c.req.json();
1225
+ } catch {
1226
+ return c.json({ error: "Invalid JSON body" }, 400);
1227
+ }
1228
+ if (typeof body.title !== "string" || body.title.trim().length === 0 || body.title.length > 5e3) {
1229
+ return c.json({ error: "invalid_title" }, 400);
1230
+ }
1231
+ if (typeof body.url !== "string" || body.url.trim().length === 0 || body.url.length > 2048 || !isCanonicalGithubIssueUrl(body.url, project.repository.slug, issueNumber)) {
1232
+ return c.json({ error: "invalid_url" }, 400);
1233
+ }
1234
+ if (!runIssueTriage) return c.json({ error: "triage_unavailable" }, 503);
1235
+ const branch = `factory/issue-${issueNumber}`;
1236
+ const projectPath = computeWorktreePath(sandboxRow.sandboxWorkdir, branch);
1237
+ await github.addIssueLabels(Number(project.installation.externalId), project.repository.slug, issueNumber, [
1238
+ "auto-triaged"
1239
+ ]);
1240
+ const result = await runIssueTriage({
1241
+ repository: project.repository.slug,
1242
+ issueNumber,
1243
+ issueTitle: body.title,
1244
+ issueUrl: body.url,
1245
+ labels: parseStringList(body.labels),
1246
+ installationId: Number(project.installation.externalId),
1247
+ resourceId: project.factoryProjectId,
1248
+ projectPath,
1249
+ branch,
1250
+ defaultModelId: await resolveFactoryDefaultModelId(options.projects, project.factoryProjectId)
1251
+ });
1252
+ await emitAudit?.({
1253
+ context: loose(c),
1254
+ input: {
1255
+ action: "factory.triage.started",
1256
+ factoryProjectId: project.factoryProjectId,
1257
+ projectRepositoryId: project.id,
1258
+ targets: [{ type: "issue", id: String(issueNumber), name: body.title }],
1259
+ metadata: { issueNumber, branch, threadId: result.threadId }
1260
+ }
1261
+ });
1262
+ return c.json(
1263
+ {
1264
+ ok: true,
1265
+ threadId: result.threadId,
1266
+ projectPath: result.projectPath ?? projectPath,
1267
+ branch: result.branch ?? branch
1268
+ },
1269
+ 202
1270
+ );
1271
+ }
1272
+ })
1273
+ );
1274
+ routes.push(
1275
+ registerApiRoute("/web/github/projects/:id/prs", {
1276
+ method: "GET",
1277
+ requiresAuth: false,
1278
+ handler: async (c) => {
1279
+ const loaded = await loadOrgProject({ github, auth, c: loose(c) });
1280
+ if ("response" in loaded) return loaded.response;
1281
+ const page = parseListPage(c.req.query("page"));
1282
+ if (page === null) return c.json({ error: "invalid_page" }, 400);
1283
+ try {
1284
+ const { pullRequests, nextCursor } = await github.versionControl.listPullRequests({
1285
+ connection: {
1286
+ type: "app-installation",
1287
+ installationId: Number(loaded.project.installation.externalId)
1288
+ },
1289
+ sourceId: loaded.project.repository.slug,
1290
+ includeDrafts: false,
1291
+ cursor: String(page)
1292
+ });
1293
+ const responsePullRequests = pullRequests.map((pr) => ({
1294
+ number: Number(pr.id),
1295
+ title: pr.title,
1296
+ url: pr.url,
1297
+ author: pr.author,
1298
+ baseBranch: pr.baseBranch,
1299
+ headBranch: pr.headBranch,
1300
+ createdAt: pr.createdAt,
1301
+ updatedAt: pr.updatedAt
1302
+ }));
1303
+ await ingestPolledEvents(
1304
+ responsePullRequests.map((pullRequest) => polledPullRequestEvent(loaded.project, pullRequest)),
1305
+ options.ingestFactoryEvent
1306
+ );
1307
+ return c.json({
1308
+ pullRequests: responsePullRequests,
1309
+ nextPage: nextCursor === null ? null : Number(nextCursor)
1310
+ });
1311
+ } catch (err) {
1312
+ return c.json(
1313
+ { error: "github_fetch_failed", message: err instanceof Error ? err.message : String(err) },
1314
+ 502
1315
+ );
1316
+ }
1317
+ }
1318
+ })
1319
+ );
1320
+ routes.push(
1321
+ registerApiRoute("/web/github/projects/:id/settings", {
1322
+ method: "GET",
1323
+ requiresAuth: false,
1324
+ handler: async (c) => {
1325
+ const loaded = await loadOrgProject({ github, auth, c: loose(c) });
1326
+ if ("response" in loaded) return loaded.response;
1327
+ return c.json({ setupCommand: loaded.project.setupCommand });
1328
+ }
1329
+ })
1330
+ );
1331
+ routes.push(
1332
+ registerApiRoute("/web/github/projects/:id/settings", {
1333
+ method: "POST",
1334
+ requiresAuth: false,
1335
+ handler: async (c) => {
1336
+ const loaded = await loadOrgProject({ github, auth, c: loose(c) });
1337
+ if ("response" in loaded) return loaded.response;
1338
+ let body;
1339
+ try {
1340
+ body = await c.req.json();
1341
+ } catch {
1342
+ return c.json({ error: "Invalid JSON body" }, 400);
1343
+ }
1344
+ if (body.setupCommand !== null && typeof body.setupCommand !== "string") {
1345
+ return c.json({ error: "Invalid setupCommand" }, 400);
1346
+ }
1347
+ if (typeof body.setupCommand === "string" && body.setupCommand.length > 2e3) {
1348
+ return c.json({ error: "setupCommand too long (max 2000 characters)" }, 400);
1349
+ }
1350
+ if (typeof body.setupCommand === "string" && /[\0-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(body.setupCommand)) {
1351
+ return c.json({ error: "setupCommand contains control characters" }, 400);
1352
+ }
1353
+ const setupCommand = typeof body.setupCommand === "string" && body.setupCommand.trim().length > 0 ? body.setupCommand.trim() : null;
1354
+ await github.sourceControlStorage.projectRepositories.update({
1355
+ orgId: loaded.project.installation.orgId,
1356
+ id: loaded.project.id,
1357
+ input: { setupCommand }
1358
+ });
1359
+ return c.json({ setupCommand });
1360
+ }
1361
+ })
1362
+ );
1363
+ routes.push(...buildProjectGitRoutes({ github, auth, fleet, storage, emitAudit }));
1364
+ return routes;
1365
+ }
1366
+ async function loadOrgProject(options) {
1367
+ const { github, auth, c } = options;
1368
+ const resolved = await resolveOrgTenant(c, auth);
1369
+ if ("response" in resolved) return { response: resolved.response };
1370
+ const { orgId, userId } = resolved.tenant;
1371
+ const projectRepositoryId = c.req.param("id");
1372
+ if (!projectRepositoryId) {
1373
+ return { response: c.json({ error: "Project repository not found" }, 404) };
1374
+ }
1375
+ const project = await resolveProjectRepository({ github, orgId, projectRepositoryId });
1376
+ if (!project) {
1377
+ return { response: c.json({ error: "Project repository not found" }, 404) };
1378
+ }
1379
+ return { project, userId };
1380
+ }
1381
+ function identityFromUser(user) {
1382
+ const u = user;
1383
+ return { name: u?.name ?? null, email: u?.email ?? null };
1384
+ }
1385
+ async function resolveProjectSandbox(options) {
1386
+ const { fleet, sandboxRow } = options;
1387
+ if (!sandboxRow.sandboxId) {
1388
+ throw new MaterializeError("Project sandbox is not provisioned. Open the project first.", "clone-failed");
1389
+ }
1390
+ return fleet.reattachSandbox(sandboxRow.sandboxId);
1391
+ }
1392
+ async function loadOrCreateSandboxRow(github, project, userId) {
1393
+ return github.sourceControlStorage.sandboxes.getOrCreate({ projectRepository: project, userId });
1394
+ }
1395
+ async function prepareProject(options) {
1396
+ const { github, fleet, project, userId, onProgress } = options;
1397
+ const sandboxRow = await loadOrCreateSandboxRow(github, project, userId);
1398
+ const sandbox = await ensureProjectSandbox({
1399
+ fleet,
1400
+ row: sandboxRow,
1401
+ storage: github.sourceControlStorage.sandboxes,
1402
+ onProgress
1403
+ });
1404
+ const fresh = await github.sourceControlStorage.sandboxes.getById({ id: sandboxRow.id });
1405
+ const access = await github.versionControl.getRepositoryAccess({
1406
+ orgId: project.installation.orgId,
1407
+ repositoryId: project.repository.id
1408
+ });
1409
+ if (!access.authorization) {
1410
+ throw new MaterializeError("Repository access did not include a bearer token.", "clone-failed");
1411
+ }
1412
+ const finalRow = fresh ?? sandboxRow;
1413
+ await materializeRepo({
1414
+ row: finalRow,
1415
+ repoInfo: { repoFullName: project.repository.slug, defaultBranch: project.defaultBranch },
1416
+ sandbox,
1417
+ token: access.authorization.token,
1418
+ storage: github.sourceControlStorage.sandboxes,
1419
+ onProgress
1420
+ });
1421
+ const result = {
1422
+ resourceId: project.factoryProjectId,
1423
+ factoryProjectId: project.factoryProjectId,
1424
+ projectRepositoryId: project.id,
1425
+ sandboxId: finalRow.sandboxId,
1426
+ sandboxWorkdir: finalRow.sandboxWorkdir
1427
+ };
1428
+ const done = { phase: "done", message: "Workspace ready." };
1429
+ onProgress?.(done);
1430
+ return result;
1431
+ }
1432
+ function ensureErrorPayload(err) {
1433
+ if (err instanceof SandboxBudgetError) {
1434
+ return { status: 429, body: { error: err.code, message: err.message } };
1435
+ }
1436
+ if (err instanceof MaterializeError) {
1437
+ return { status: 502, body: { error: err.code, message: err.message } };
1438
+ }
1439
+ return {
1440
+ status: 500,
1441
+ body: { error: "materialize_failed", message: err instanceof Error ? err.message : String(err) }
1442
+ };
1443
+ }
1444
+ function gitErrorResponse(c, err) {
1445
+ if (err instanceof WorktreeError) {
1446
+ return c.json({ error: err.code, message: err.message }, err.code === "invalid-branch" ? 400 : 502);
1447
+ }
1448
+ if (err instanceof MaterializeError) {
1449
+ return c.json({ error: err.code, message: err.message }, 502);
1450
+ }
1451
+ return c.json({ error: "git_failed", message: err instanceof Error ? err.message : String(err) }, 500);
1452
+ }
1453
+ async function loadOwnedProject(options) {
1454
+ const { github, auth, fleet, c } = options;
1455
+ const resolved = await resolveOrgTenant(c, auth);
1456
+ if ("response" in resolved) return { response: resolved.response };
1457
+ const { orgId, userId } = resolved.tenant;
1458
+ if (!fleet.enabled) {
1459
+ return {
1460
+ response: c.json({ error: "sandbox_not_configured", message: "No sandbox provider is configured." }, 503)
1461
+ };
1462
+ }
1463
+ const projectRepositoryId = c.req.param("id");
1464
+ if (!projectRepositoryId) {
1465
+ return { response: c.json({ error: "Project repository not found" }, 404) };
1466
+ }
1467
+ const project = await resolveProjectRepository({ github, orgId, projectRepositoryId });
1468
+ if (!project) {
1469
+ return { response: c.json({ error: "Project repository not found" }, 404) };
1470
+ }
1471
+ const sandboxRow = await loadOrCreateSandboxRow(github, project, userId);
1472
+ return { orgId, userId, project, sandboxRow };
1473
+ }
1474
+ function buildProjectGitRoutes({
1475
+ github,
1476
+ auth,
1477
+ fleet,
1478
+ storage,
1479
+ emitAudit
1480
+ }) {
1481
+ return [
1482
+ // ── Create / list Factory sessions ──────────────────────────────────────
1483
+ registerApiRoute("/web/github/projects/:id/sessions", {
1484
+ method: "GET",
1485
+ requiresAuth: false,
1486
+ handler: async (c) => {
1487
+ const resolved = await resolveOrgTenant(loose(c), auth);
1488
+ if ("response" in resolved) return resolved.response;
1489
+ const { orgId, userId } = resolved.tenant;
1490
+ const projectRepositoryId = c.req.param("id");
1491
+ const project = projectRepositoryId ? await resolveProjectRepository({ github, orgId, projectRepositoryId }) : null;
1492
+ if (!project) return c.json({ error: "Project repository not found" }, 404);
1493
+ const sessions = await github.sourceControlStorage.sessions.list({ projectRepositoryId: project.id, userId });
1494
+ return c.json({ sessions });
1495
+ }
1496
+ }),
1497
+ registerApiRoute("/web/github/projects/:id/sessions", {
1498
+ method: "POST",
1499
+ requiresAuth: false,
1500
+ handler: async (c) => {
1501
+ const resolved = await resolveOrgTenant(loose(c), auth);
1502
+ if ("response" in resolved) return resolved.response;
1503
+ const { orgId, userId } = resolved.tenant;
1504
+ const projectRepositoryId = c.req.param("id");
1505
+ const project = projectRepositoryId ? await resolveProjectRepository({ github, orgId, projectRepositoryId }) : null;
1506
+ if (!project) return c.json({ error: "Project repository not found" }, 404);
1507
+ let body;
1508
+ try {
1509
+ body = await c.req.json();
1510
+ } catch {
1511
+ return c.json({ error: "Invalid JSON body" }, 400);
1512
+ }
1513
+ if (!isValidGitRef(body.branch)) return c.json({ error: "Invalid branch" }, 400);
1514
+ const baseBranch = body.baseBranch === void 0 ? project.defaultBranch : body.baseBranch;
1515
+ if (!isValidGitRef(baseBranch)) return c.json({ error: "Invalid baseBranch" }, 400);
1516
+ const session = await github.sourceControlStorage.sessions.create({
1517
+ sessionId: randomUUID(),
1518
+ projectRepositoryId: project.id,
1519
+ orgId,
1520
+ userId,
1521
+ branch: body.branch,
1522
+ baseBranch
1523
+ });
1524
+ return c.json({ session });
1525
+ }
1526
+ }),
1527
+ registerApiRoute("/web/user-sessions/:sessionId", {
1528
+ method: "GET",
1529
+ requiresAuth: false,
1530
+ handler: async (c) => {
1531
+ const resolved = await resolveOrgTenant(loose(c), auth);
1532
+ if ("response" in resolved) return resolved.response;
1533
+ const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
1534
+ if (!session || session.orgId !== resolved.tenant.orgId || session.userId !== resolved.tenant.userId) {
1535
+ return c.json({ error: "Session not found" }, 404);
1536
+ }
1537
+ return c.json({ session });
1538
+ }
1539
+ }),
1540
+ registerApiRoute("/web/user-sessions/:sessionId", {
1541
+ method: "DELETE",
1542
+ requiresAuth: false,
1543
+ handler: async (c) => {
1544
+ const resolved = await resolveOrgTenant(loose(c), auth);
1545
+ if ("response" in resolved) return resolved.response;
1546
+ const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
1547
+ if (!session || session.orgId !== resolved.tenant.orgId || session.userId !== resolved.tenant.userId) {
1548
+ return c.json({ error: "Session not found" }, 404);
1549
+ }
1550
+ let sandbox;
1551
+ if (session.sandboxId) {
1552
+ try {
1553
+ sandbox = await fleet.reattachSandbox(session.sandboxId);
1554
+ } catch {
1555
+ }
1556
+ await fleet.teardownSandbox(
1557
+ {
1558
+ sandboxId: session.sandboxId,
1559
+ setSandboxId: async () => {
1560
+ },
1561
+ clear: async () => {
1562
+ await github.sourceControlStorage.sessions.setSandbox({
1563
+ id: session.id,
1564
+ sandboxId: null,
1565
+ sandboxWorkdir: session.sandboxWorkdir ?? ""
1566
+ });
1567
+ }
1568
+ },
1569
+ sandbox
1570
+ );
1571
+ }
1572
+ await github.sourceControlStorage.sessions.delete(session.id);
1573
+ return c.json({ removed: true });
1574
+ }
1575
+ }),
1576
+ // ── Stage all + commit inside a Factory session workspace ──────────────
1577
+ registerApiRoute("/web/github/projects/:id/commit", {
1578
+ method: "POST",
1579
+ requiresAuth: false,
1580
+ handler: async (c) => {
1581
+ const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
1582
+ if ("response" in owned) return owned.response;
1583
+ const { userId, project } = owned;
1584
+ let body;
1585
+ try {
1586
+ body = await c.req.json();
1587
+ } catch {
1588
+ return c.json({ error: "Invalid JSON body" }, 400);
1589
+ }
1590
+ if (typeof body.message !== "string" || body.message.trim().length === 0 || body.message.length > 5e3) {
1591
+ return c.json({ error: "Invalid message" }, 400);
1592
+ }
1593
+ const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
1594
+ if (!sessionWorkspace) {
1595
+ return c.json({ error: "Invalid sessionId" }, 400);
1596
+ }
1597
+ const { workdir, sandboxBinding } = sessionWorkspace;
1598
+ try {
1599
+ return await withProjectLock({
1600
+ key: `${project.id}:${userId}`,
1601
+ storage,
1602
+ fn: async () => {
1603
+ const sandbox = await resolveProjectSandbox({ fleet, sandboxRow: sandboxBinding });
1604
+ const result = await commitAll(
1605
+ sandbox,
1606
+ workdir,
1607
+ body.message,
1608
+ identityFromUser(await auth.ensureUser(loose(c)))
1609
+ );
1610
+ if (result.committed) {
1611
+ await emitAudit?.({
1612
+ context: loose(c),
1613
+ input: {
1614
+ action: "factory.git.commit",
1615
+ factoryProjectId: project.factoryProjectId,
1616
+ projectRepositoryId: project.id,
1617
+ targets: [{ type: "session", id: sessionWorkspace.session.sessionId }],
1618
+ metadata: { sessionId: sessionWorkspace.session.sessionId }
1619
+ }
1620
+ });
1621
+ }
1622
+ return c.json({ committed: result.committed });
1623
+ }
1624
+ });
1625
+ } catch (err) {
1626
+ return gitErrorResponse(loose(c), err);
1627
+ }
1628
+ }
1629
+ }),
1630
+ // ── Push a branch back to GitHub ────────────────────────────────────────
1631
+ registerApiRoute("/web/github/projects/:id/push", {
1632
+ method: "POST",
1633
+ requiresAuth: false,
1634
+ handler: async (c) => {
1635
+ const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
1636
+ if ("response" in owned) return owned.response;
1637
+ const { orgId, userId, project } = owned;
1638
+ let body;
1639
+ try {
1640
+ body = await c.req.json();
1641
+ } catch {
1642
+ return c.json({ error: "Invalid JSON body" }, 400);
1643
+ }
1644
+ if (!isValidGitRef(body.branch)) {
1645
+ return c.json({ error: "Invalid branch" }, 400);
1646
+ }
1647
+ const branch = body.branch;
1648
+ const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
1649
+ if (!sessionWorkspace) {
1650
+ return c.json({ error: "Invalid sessionId" }, 400);
1651
+ }
1652
+ const { workdir, sandboxBinding } = sessionWorkspace;
1653
+ try {
1654
+ return await withProjectLock({
1655
+ key: `${project.id}:${userId}`,
1656
+ storage,
1657
+ fn: async () => {
1658
+ const sandbox = await resolveProjectSandbox({ fleet, sandboxRow: sandboxBinding });
1659
+ const access = await github.versionControl.getRepositoryAccess({
1660
+ orgId,
1661
+ repositoryId: project.repository.id
1662
+ });
1663
+ if (!access.authorization) throw new Error("Repository access did not include a bearer token.");
1664
+ await pushBranch(sandbox, workdir, branch, access.authorization.token, project.repository.slug);
1665
+ await emitAudit?.({
1666
+ context: loose(c),
1667
+ input: {
1668
+ action: "factory.git.push",
1669
+ factoryProjectId: project.factoryProjectId,
1670
+ projectRepositoryId: project.id,
1671
+ targets: [{ type: "branch", id: branch }],
1672
+ metadata: { branch, sessionId: sessionWorkspace.session.sessionId }
1673
+ }
1674
+ });
1675
+ return c.json({ pushed: true, branch });
1676
+ }
1677
+ });
1678
+ } catch (err) {
1679
+ return gitErrorResponse(loose(c), err);
1680
+ }
1681
+ }
1682
+ }),
1683
+ // ── Open a pull request through the version-control capability ─────────
1684
+ registerApiRoute("/web/github/projects/:id/pr", {
1685
+ method: "POST",
1686
+ requiresAuth: false,
1687
+ handler: async (c) => {
1688
+ const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
1689
+ if ("response" in owned) return owned.response;
1690
+ const { orgId, userId, project } = owned;
1691
+ let body;
1692
+ try {
1693
+ body = await c.req.json();
1694
+ } catch {
1695
+ return c.json({ error: "Invalid JSON body" }, 400);
1696
+ }
1697
+ if (!isValidGitRef(body.branch)) {
1698
+ return c.json({ error: "Invalid branch" }, 400);
1699
+ }
1700
+ const base = body.base === void 0 ? project.defaultBranch : body.base;
1701
+ if (!isValidGitRef(base)) {
1702
+ return c.json({ error: "Invalid base" }, 400);
1703
+ }
1704
+ if (typeof body.title !== "string" || body.title.trim().length === 0 || body.title.length > 256) {
1705
+ return c.json({ error: "Invalid title" }, 400);
1706
+ }
1707
+ if (body.body !== void 0 && (typeof body.body !== "string" || body.body.length > 65536)) {
1708
+ return c.json({ error: "Invalid body" }, 400);
1709
+ }
1710
+ const head = body.branch;
1711
+ const title = body.title;
1712
+ const prBody = body.body;
1713
+ const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
1714
+ if (!sessionWorkspace) {
1715
+ return c.json({ error: "Invalid sessionId" }, 400);
1716
+ }
1717
+ try {
1718
+ return await withProjectLock({
1719
+ key: `${project.id}:${userId}`,
1720
+ storage,
1721
+ fn: async () => {
1722
+ const result = await github.versionControl.createPullRequest({
1723
+ connection: {
1724
+ type: "app-installation",
1725
+ installationId: Number(project.installation.externalId)
1726
+ },
1727
+ sourceId: project.repository.slug,
1728
+ baseBranch: base,
1729
+ headBranch: head,
1730
+ title,
1731
+ body: prBody
1732
+ });
1733
+ await emitAudit?.({
1734
+ context: loose(c),
1735
+ input: {
1736
+ action: "factory.git.pr_opened",
1737
+ factoryProjectId: project.factoryProjectId,
1738
+ projectRepositoryId: project.id,
1739
+ targets: [{ type: "pull_request", id: result.url, name: title }],
1740
+ metadata: { branch: head, base, url: result.url }
1741
+ }
1742
+ });
1743
+ const pullRequestNumber = pullRequestNumberFromUrl(result.url, project.repository.slug);
1744
+ if (pullRequestNumber) {
1745
+ const sessionId = sessionWorkspace.session.sessionId;
1746
+ await subscribeToPullRequest(
1747
+ {
1748
+ orgId,
1749
+ installationExternalId: project.installation.externalId,
1750
+ projectRepositoryId: project.id,
1751
+ repositoryExternalId: project.repository.externalId,
1752
+ repositorySlug: project.repository.slug,
1753
+ changeRequestId: pullRequestNumber.toString(),
1754
+ sessionId,
1755
+ ownerId: userId,
1756
+ resourceId: sessionId,
1757
+ threadId: sessionId,
1758
+ source: "factory-pr-create",
1759
+ subscribedByUserId: userId
1760
+ },
1761
+ github.integrationStorage
1762
+ ).catch((error) => {
1763
+ console.warn(
1764
+ `[GitHub] Pull request ${result.url} was created but automatic subscription failed.`,
1765
+ error
1766
+ );
1767
+ });
1768
+ }
1769
+ return c.json({ url: result.url });
1770
+ }
1771
+ });
1772
+ } catch (err) {
1773
+ return c.json(
1774
+ { error: "github_pr_create_failed", message: err instanceof Error ? err.message : String(err) },
1775
+ 502
1776
+ );
1777
+ }
1778
+ }
1779
+ }),
1780
+ // ── Tear down the caller's sandbox for a project ────────────────────────
1781
+ // Per-user teardown only: drops the caller's `(project, user)` sandbox
1782
+ // binding and stops the VM, freeing a slot in the per-replica budget. Project
1783
+ // deletion at the org level is out of scope (org admin model is later).
1784
+ registerApiRoute("/web/github/projects/:id/sandbox", {
1785
+ method: "DELETE",
1786
+ requiresAuth: false,
1787
+ handler: async (c) => {
1788
+ const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
1789
+ if ("response" in owned) return owned.response;
1790
+ const { userId, project, sandboxRow } = owned;
1791
+ if (!sandboxRow.sandboxId) {
1792
+ return c.json({ tornDown: false });
1793
+ }
1794
+ try {
1795
+ return await withProjectLock({
1796
+ key: `${project.id}:${userId}`,
1797
+ storage,
1798
+ fn: async () => {
1799
+ const sandbox = await fleet.reattachSandbox(sandboxRow.sandboxId);
1800
+ await teardownProjectSandbox({
1801
+ fleet,
1802
+ row: sandboxRow,
1803
+ storage: github.sourceControlStorage.sandboxes,
1804
+ sandbox
1805
+ });
1806
+ return c.json({ tornDown: true });
1807
+ }
1808
+ });
1809
+ } catch (err) {
1810
+ return gitErrorResponse(loose(c), err);
1811
+ }
1812
+ }
1813
+ })
1814
+ ];
1815
+ }
1816
+ async function resolveSessionWorkspace(github, projectId, userId, sessionId) {
1817
+ if (typeof sessionId !== "string") {
1818
+ return void 0;
1819
+ }
1820
+ const session = await github.sourceControlStorage.sessions.getBySessionId(sessionId);
1821
+ if (session?.projectRepositoryId !== projectId || session.userId !== userId || !session.sandboxId || !session.sandboxWorkdir) {
1822
+ return void 0;
1823
+ }
1824
+ return {
1825
+ session,
1826
+ workdir: session.sandboxWorkdir,
1827
+ sandboxBinding: {
1828
+ id: session.id,
1829
+ projectRepositoryId: session.projectRepositoryId,
1830
+ userId: session.userId,
1831
+ sandboxId: session.sandboxId,
1832
+ sandboxWorkdir: session.sandboxWorkdir,
1833
+ materializedAt: session.materializedAt,
1834
+ createdAt: session.createdAt
1835
+ }
1836
+ };
1837
+ }
1838
+
1839
+ // src/integrations/github/session-subscriptions.ts
1840
+ import { createTool } from "@mastra/core/tools";
1841
+ import { z } from "zod";
1842
+ function sessionUserId(user) {
1843
+ return user?.workosId ?? user?.id;
1844
+ }
1845
+ function sessionOrgId(user) {
1846
+ return user?.organizationId;
1847
+ }
1848
+ var pullRequestInputSchema = z.object({
1849
+ pullRequest: z.union([z.number().int().positive(), z.string().min(1)])
1850
+ });
1851
+ function parsePullRequest(value, expectedRepo) {
1852
+ if (typeof value === "number") return value;
1853
+ if (/^\d+$/.test(value)) return Number(value);
1854
+ const match = value.match(/^https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)\/?$/i);
1855
+ if (!match || match[1].toLowerCase() !== expectedRepo.toLowerCase()) {
1856
+ throw new Error(`Pull request must belong to ${expectedRepo}.`);
1857
+ }
1858
+ return Number(match[2]);
1859
+ }
1860
+ function isGithubProjectSession(requestContext) {
1861
+ const context = requestContext.get("controller");
1862
+ const user = requestContext.get("user");
1863
+ return Boolean(
1864
+ context?.threadId && context.getState().projectRepositoryId && sessionOrgId(user) && sessionUserId(user)
1865
+ );
1866
+ }
1867
+ async function resolveSessionTarget(requestContext, github) {
1868
+ const context = requestContext.get("controller");
1869
+ const user = requestContext.get("user");
1870
+ const orgId = sessionOrgId(user);
1871
+ const userId = sessionUserId(user);
1872
+ const projectRepositoryId = context?.getState().projectRepositoryId;
1873
+ if (!context || !context.threadId || !projectRepositoryId || !orgId || !userId) {
1874
+ throw new Error("GitHub subscriptions require an authenticated repository session with an active thread.");
1875
+ }
1876
+ const projectRepository = await github.sourceControlStorage.projectRepositories.get({
1877
+ orgId,
1878
+ id: projectRepositoryId
1879
+ });
1880
+ if (!projectRepository) throw new Error("Project repository not found for this organization.");
1881
+ const connection = await github.sourceControlStorage.connections.get({ orgId, id: projectRepository.connectionId });
1882
+ if (!connection) throw new Error("Source-control connection not found for this organization.");
1883
+ const repository = await github.sourceControlStorage.repositories.get({ orgId, id: projectRepository.repositoryId });
1884
+ if (!repository) throw new Error("Repository not found for this organization.");
1885
+ const installation = await github.sourceControlStorage.installations.get({ orgId, id: connection.installationId });
1886
+ if (!installation) throw new Error("Source-control installation not found for this organization.");
1887
+ return { context, projectRepository, connection, installation, repository, orgId, userId };
1888
+ }
1889
+ async function verifyPullRequest(target, pullRequest, github) {
1890
+ const [owner, repo] = target.repository.slug.split("/");
1891
+ if (!owner || !repo) throw new Error("GitHub repository is invalid.");
1892
+ const octokit = github.getInstallationOctokit(Number(target.installation.externalId));
1893
+ const { data } = await octokit.pulls.get({ owner, repo, pull_number: pullRequest });
1894
+ if (String(data.base.repo.id) !== target.repository.externalId)
1895
+ throw new Error("Pull request repository does not match the active project repository.");
1896
+ }
1897
+ async function subscriptionInput(target, pullRequestNumber) {
1898
+ return {
1899
+ orgId: target.orgId,
1900
+ installationExternalId: target.installation.externalId,
1901
+ projectRepositoryId: target.projectRepository.id,
1902
+ repositoryExternalId: target.repository.externalId,
1903
+ repositorySlug: target.repository.slug,
1904
+ changeRequestId: String(pullRequestNumber),
1905
+ sessionId: target.context.session.id,
1906
+ ownerId: target.context.session.ownerId,
1907
+ resourceId: target.connection.factoryProjectId,
1908
+ threadId: target.context.threadId,
1909
+ sessionScope: target.context.scope,
1910
+ source: "explicit-tool",
1911
+ subscribedByUserId: target.userId
1912
+ };
1913
+ }
1914
+ async function subscribeCurrentSessionToPullRequest(requestContext, pullRequest, source, github) {
1915
+ if (source === "auto-gh-pr-create" && !isGithubProjectSession(requestContext)) return void 0;
1916
+ const target = await resolveSessionTarget(requestContext, github);
1917
+ const number = parsePullRequest(pullRequest, target.repository.slug);
1918
+ await verifyPullRequest(target, number, github);
1919
+ await subscribeToPullRequest({ ...await subscriptionInput(target, number), source }, github.integrationStorage);
1920
+ return number;
1921
+ }
1922
+ async function unsubscribeCurrentSessionFromPullRequest(requestContext, pullRequest, github) {
1923
+ const target = await resolveSessionTarget(requestContext, github);
1924
+ const number = parsePullRequest(pullRequest, target.repository.slug);
1925
+ await unsubscribeFromPullRequest(await subscriptionInput(target, number), github.integrationStorage);
1926
+ return number;
1927
+ }
1928
+ function createGithubSubscriptionTools(requestContext, github) {
1929
+ const context = requestContext.get("controller");
1930
+ const user = requestContext.get("user");
1931
+ if (!context?.getState().projectRepositoryId || !sessionOrgId(user) || !sessionUserId(user)) return {};
1932
+ return {
1933
+ github_subscribe_pr: createTool({
1934
+ id: "github_subscribe_pr",
1935
+ 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.",
1936
+ inputSchema: pullRequestInputSchema,
1937
+ execute: async ({ pullRequest }) => {
1938
+ const number = await subscribeCurrentSessionToPullRequest(requestContext, pullRequest, "explicit-tool", github);
1939
+ return { subscribed: true, pullRequestNumber: number };
1940
+ }
1941
+ }),
1942
+ github_unsubscribe_pr: createTool({
1943
+ id: "github_unsubscribe_pr",
1944
+ 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.",
1945
+ inputSchema: pullRequestInputSchema,
1946
+ execute: async ({ pullRequest }) => {
1947
+ const number = await unsubscribeCurrentSessionFromPullRequest(requestContext, pullRequest, github);
1948
+ return { subscribed: false, pullRequestNumber: number };
1949
+ }
1950
+ })
1951
+ };
1952
+ }
1953
+ function stripHeredocBodies(command) {
1954
+ const lines = command.split("\n");
1955
+ const executableLines = [];
1956
+ let delimiter;
1957
+ for (const line of lines) {
1958
+ if (delimiter) {
1959
+ if (line.trim() === delimiter) delimiter = void 0;
1960
+ continue;
1961
+ }
1962
+ executableLines.push(line);
1963
+ const heredoc = line.match(/<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/);
1964
+ delimiter = heredoc?.[2];
1965
+ }
1966
+ return executableLines.join("\n");
1967
+ }
1968
+ function parseCreatedPullRequest(context) {
1969
+ if (context.toolName !== "execute_command" || context.error) return void 0;
1970
+ const command = context.input?.command;
1971
+ if (typeof command !== "string" || !/(?:^|\n|;|&&|\|\|)\s*gh\s+pr\s+create(?:\s|$)/.test(stripHeredocBodies(command))) {
1972
+ return void 0;
1973
+ }
1974
+ const output = context.output;
1975
+ const stdout = typeof context.output === "string" ? context.output : output?.stdout ?? output?.result;
1976
+ if (typeof stdout !== "string") return void 0;
1977
+ const urls = stdout.match(/https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/\d+/g) ?? [];
1978
+ return urls.length === 1 ? urls[0] : void 0;
1979
+ }
1980
+
1981
+ // src/integrations/platform/api-client.ts
1982
+ function platformApiClientConfigFromEnv() {
1983
+ const sharedApiUrl = process.env.MASTRA_SHARED_API_URL?.trim() || "https://platform.mastra.ai/v1";
1984
+ const accessToken = process.env.MASTRA_PLATFORM_SECRET_KEY?.trim();
1985
+ if (!accessToken) {
1986
+ throw new Error("Platform integration: missing required environment variable MASTRA_PLATFORM_SECRET_KEY.");
1987
+ }
1988
+ return { baseUrl: normalizeSharedApiUrl(sharedApiUrl), accessToken };
1989
+ }
1990
+ function normalizeSharedApiUrl(sharedApiUrl) {
1991
+ return sharedApiUrl.replace(/\/+$/, "").replace(/\/v1$/, "");
1992
+ }
1993
+ var PlatformApiError = class extends Error {
1994
+ status;
1995
+ retryAfterSeconds;
1996
+ constructor(message, status, retryAfterSeconds = null) {
1997
+ super(message);
1998
+ this.name = "PlatformApiError";
1999
+ this.status = status;
2000
+ this.retryAfterSeconds = retryAfterSeconds;
2001
+ }
2002
+ };
2003
+ var PlatformApiClient = class {
2004
+ #baseUrl;
2005
+ #accessToken;
2006
+ #fetch;
2007
+ constructor(config) {
2008
+ const missing = ["baseUrl", "accessToken"].filter((field) => !config[field]);
2009
+ if (missing.length > 0) {
2010
+ throw new Error(`Platform integration: missing required config field(s): ${missing.join(", ")}.`);
2011
+ }
2012
+ this.#baseUrl = config.baseUrl.replace(/\/+$/, "");
2013
+ this.#accessToken = config.accessToken;
2014
+ this.#fetch = config.fetchImpl ?? globalThis.fetch;
2015
+ }
2016
+ async request(method, path2, body, options) {
2017
+ const response = await this.#send(method, path2, body, options);
2018
+ if (!response.ok) {
2019
+ const message = redact(await extractError(response), this.#accessToken);
2020
+ const retryAfterSeconds = parseRetryAfter(response.headers.get("retry-after"));
2021
+ logPlatformError("Platform API request failed", {
2022
+ method,
2023
+ path: path2,
2024
+ status: response.status,
2025
+ retryAfterSeconds,
2026
+ message
2027
+ });
2028
+ throw new PlatformApiError(message, response.status, retryAfterSeconds);
2029
+ }
2030
+ if (response.status === 204) return void 0;
2031
+ return await response.json();
2032
+ }
2033
+ async requestRedirect(method, path2, options) {
2034
+ const response = await this.#send(method, path2, void 0, options, "manual");
2035
+ if (response.status >= 300 && response.status < 400) {
2036
+ const location = response.headers.get("location");
2037
+ if (location) return location;
2038
+ }
2039
+ if (!response.ok) {
2040
+ const message = redact(await extractError(response), this.#accessToken);
2041
+ const retryAfterSeconds = parseRetryAfter(response.headers.get("retry-after"));
2042
+ logPlatformError("Platform API redirect request failed", {
2043
+ method,
2044
+ path: path2,
2045
+ status: response.status,
2046
+ retryAfterSeconds,
2047
+ message
2048
+ });
2049
+ throw new PlatformApiError(message, response.status, retryAfterSeconds);
2050
+ }
2051
+ logPlatformError("Platform API request did not return a redirect", { method, path: path2, status: response.status });
2052
+ throw new PlatformApiError("Platform API request did not return a redirect.", response.status);
2053
+ }
2054
+ async #send(method, path2, body, options, redirect) {
2055
+ const headers = {
2056
+ accept: "application/json",
2057
+ authorization: `Bearer ${this.#accessToken}`
2058
+ };
2059
+ const timeoutSignal = AbortSignal.timeout(15e3);
2060
+ const init = {
2061
+ method,
2062
+ headers,
2063
+ redirect,
2064
+ signal: options?.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal
2065
+ };
2066
+ if (body !== void 0) {
2067
+ headers["content-type"] = "application/json";
2068
+ init.body = JSON.stringify(body);
2069
+ }
2070
+ try {
2071
+ return await this.#fetch(`${this.#baseUrl}${path2}`, init);
2072
+ } catch (error) {
2073
+ if (error instanceof Error && error.message.includes(this.#accessToken)) {
2074
+ const redacted = new Error(redact(error.message, this.#accessToken));
2075
+ redacted.name = error.name;
2076
+ logPlatformError("Platform API transport error", {
2077
+ method,
2078
+ path: path2,
2079
+ name: redacted.name,
2080
+ message: redacted.message
2081
+ });
2082
+ throw redacted;
2083
+ }
2084
+ logPlatformError("Platform API transport error", {
2085
+ method,
2086
+ path: path2,
2087
+ name: error instanceof Error ? error.name : void 0,
2088
+ message: error instanceof Error ? error.message : String(error)
2089
+ });
2090
+ throw error;
2091
+ }
2092
+ }
2093
+ };
2094
+ async function extractError(response) {
2095
+ try {
2096
+ const data = await response.clone().json();
2097
+ for (const field of ["detail", "error", "title"]) {
2098
+ if (typeof data[field] === "string" && data[field]) return data[field];
2099
+ }
2100
+ } catch {
2101
+ }
2102
+ return `Platform API request failed (${response.status})`;
2103
+ }
2104
+ function redact(message, accessToken) {
2105
+ return message.split(accessToken).join("[REDACTED]");
2106
+ }
2107
+ function logPlatformInfo(message, fields) {
2108
+ writePlatformLog("info", message, fields);
2109
+ }
2110
+ function logPlatformError(message, fields) {
2111
+ writePlatformLog("error", message, fields);
2112
+ }
2113
+ function writePlatformLog(level, message, fields) {
2114
+ const metadata = fields ? ` ${JSON.stringify(stripUndefined(fields))}` : "";
2115
+ process.stderr.write(`[MastraCode Web] ${level.toUpperCase()} ${message}${metadata}
2116
+ `);
2117
+ }
2118
+ function stripUndefined(fields) {
2119
+ return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0));
2120
+ }
2121
+ function parseRetryAfter(value) {
2122
+ if (!value) return null;
2123
+ const seconds = Number.parseInt(value, 10);
2124
+ return Number.isSafeInteger(seconds) && seconds >= 0 ? seconds : null;
2125
+ }
2126
+
2127
+ // src/integrations/platform/github/event-worker.ts
2128
+ import { randomUUID as randomUUID2 } from "crypto";
2129
+ import { isLeaseProvider, NoopLeaseProvider } from "@mastra/core/events";
2130
+ import { MastraWorker } from "@mastra/core/worker";
2131
+ var API_PREFIX = "/v1/server/github-app";
2132
+ var DEFAULT_POLL_INTERVAL_MS = 5e3;
2133
+ var EVENT_PAGE_SIZE = 500;
2134
+ var MIN_LEASE_TTL_MS = 3e4;
2135
+ var CURSOR_ORG_ID = "__platform_github_event_worker__";
2136
+ var CURSOR_USER_ID = "worker";
2137
+ var SUPPORTED_EVENTS = /* @__PURE__ */ new Set([
2138
+ "issues",
2139
+ "issue_comment",
2140
+ "pull_request",
2141
+ "pull_request_review",
2142
+ "pull_request_review_comment"
2143
+ ]);
2144
+ var AUTHOR_GATED_KINDS2 = /* @__PURE__ */ new Set([
2145
+ "issue-comment",
2146
+ "pull-request-comment",
2147
+ "pull-request-review",
2148
+ "pull-request-review-comment"
2149
+ ]);
2150
+ var AUTHORIZED_BOTS2 = /* @__PURE__ */ new Set(["coderabbitai[bot]", "devin-ai-integration[bot]"]);
2151
+ var AUTHORIZED_PERMISSIONS2 = /* @__PURE__ */ new Set(["admin", "maintain", "write"]);
2152
+ var PERMISSION_CHECK_TIMEOUT_MS2 = 5e3;
2153
+ var PlatformGithubEventWorker = class extends MastraWorker {
2154
+ name = "platform-github-events";
2155
+ #client;
2156
+ #controller;
2157
+ #github;
2158
+ #storage;
2159
+ #ingestFactoryEvent;
2160
+ #intervalMs;
2161
+ #now;
2162
+ #dispatch;
2163
+ #leaseOwner = randomUUID2();
2164
+ #running = false;
2165
+ #timer;
2166
+ #leaseRenewalTimer;
2167
+ #inFlight;
2168
+ #leaseProvider = NoopLeaseProvider;
2169
+ #leaseTtlMs;
2170
+ #hasLease = false;
2171
+ #startedAt = 0;
2172
+ #settings = { version: 1, repositories: {} };
2173
+ constructor(config) {
2174
+ super();
2175
+ this.#client = config.client;
2176
+ this.#controller = config.controller;
2177
+ this.#github = config.github;
2178
+ this.#storage = config.storage;
2179
+ this.#ingestFactoryEvent = config.ingestFactoryEvent;
2180
+ this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;
2181
+ if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {
2182
+ throw new Error("Platform GitHub event polling interval must be a positive number.");
2183
+ }
2184
+ this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);
2185
+ this.#now = config.now ?? Date.now;
2186
+ this.#dispatch = config.dispatch ?? dispatchGithubWebhook;
2187
+ }
2188
+ async init(deps) {
2189
+ await super.init(deps);
2190
+ this.#leaseProvider = getLeaseProvider(deps.pubsub);
2191
+ }
2192
+ async start() {
2193
+ if (this.#running) return;
2194
+ if (!this.deps) throw new Error("PlatformGithubEventWorker: call init() before start()");
2195
+ this.#startedAt = this.#now() - 1;
2196
+ this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));
2197
+ this.#running = true;
2198
+ this.deps.logger.info("Platform GitHub event polling started", {
2199
+ intervalMs: this.#intervalMs,
2200
+ leaseTtlMs: this.#leaseTtlMs
2201
+ });
2202
+ this.#schedule(0);
2203
+ }
2204
+ async stop() {
2205
+ if (!this.#running) return;
2206
+ this.#running = false;
2207
+ if (this.#timer) clearTimeout(this.#timer);
2208
+ this.#timer = void 0;
2209
+ this.#stopLeaseRenewal();
2210
+ await this.#inFlight;
2211
+ if (this.#hasLease) {
2212
+ await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => void 0);
2213
+ this.#hasLease = false;
2214
+ }
2215
+ }
2216
+ get isRunning() {
2217
+ return this.#running;
2218
+ }
2219
+ #schedule(delayMs) {
2220
+ if (!this.#running) return;
2221
+ this.#timer = setTimeout(() => {
2222
+ this.#timer = void 0;
2223
+ const run = this.#tick();
2224
+ this.#inFlight = run;
2225
+ void run.finally(() => {
2226
+ if (this.#inFlight === run) this.#inFlight = void 0;
2227
+ });
2228
+ }, delayMs);
2229
+ this.#timer.unref?.();
2230
+ }
2231
+ async #tick() {
2232
+ let nextDelay = this.#intervalMs;
2233
+ try {
2234
+ if (!await this.#ensureLease()) return;
2235
+ nextDelay = await this.#poll();
2236
+ } catch (error) {
2237
+ nextDelay = retryDelay(error, this.#intervalMs);
2238
+ this.deps?.logger.error("Platform GitHub event polling cycle failed", {
2239
+ error: error instanceof Error ? error.message : String(error),
2240
+ retryInMs: nextDelay
2241
+ });
2242
+ } finally {
2243
+ this.#schedule(nextDelay);
2244
+ }
2245
+ }
2246
+ async #ensureLease() {
2247
+ if (this.#hasLease) return true;
2248
+ const result = await this.#leaseProvider.acquireLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs);
2249
+ this.#hasLease = result.acquired;
2250
+ if (this.#hasLease) this.#startLeaseRenewal();
2251
+ return this.#hasLease;
2252
+ }
2253
+ #startLeaseRenewal() {
2254
+ if (this.#leaseRenewalTimer) return;
2255
+ this.#leaseRenewalTimer = setInterval(
2256
+ () => {
2257
+ void this.#leaseProvider.renewLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs).then((renewed) => {
2258
+ if (!renewed) {
2259
+ this.#hasLease = false;
2260
+ this.#stopLeaseRenewal();
2261
+ }
2262
+ }).catch((error) => {
2263
+ this.#hasLease = false;
2264
+ this.#stopLeaseRenewal();
2265
+ this.deps?.logger.warn("Platform GitHub event polling lease renewal failed", {
2266
+ error: error instanceof Error ? error.message : String(error)
2267
+ });
2268
+ });
2269
+ },
2270
+ Math.floor(this.#leaseTtlMs / 3)
2271
+ );
2272
+ this.#leaseRenewalTimer.unref?.();
2273
+ }
2274
+ #stopLeaseRenewal() {
2275
+ if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);
2276
+ this.#leaseRenewalTimer = void 0;
2277
+ }
2278
+ async #poll() {
2279
+ const repositories = await this.#discoverRepositories();
2280
+ let retryInMs = this.#intervalMs;
2281
+ for (const repository of repositories) {
2282
+ if (!this.#running || !this.#hasLease) break;
2283
+ try {
2284
+ await this.#pollRepository(repository.id);
2285
+ } catch (error) {
2286
+ const delay = retryDelay(error, this.#intervalMs);
2287
+ retryInMs = Math.max(retryInMs, delay);
2288
+ this.deps?.logger.error("Platform GitHub repository event polling failed", {
2289
+ repositoryId: repository.id,
2290
+ error: error instanceof Error ? error.message : String(error),
2291
+ retryInMs: delay
2292
+ });
2293
+ if (error instanceof PlatformApiError && error.status === 429) break;
2294
+ }
2295
+ }
2296
+ return retryInMs;
2297
+ }
2298
+ async #discoverRepositories() {
2299
+ const result = await this.#client.request("GET", `${API_PREFIX}/installations`);
2300
+ const repositories = /* @__PURE__ */ new Map();
2301
+ for (const installation of result.installations) {
2302
+ if (!installation.usable || installation.suspendedAt) continue;
2303
+ const page = await this.#client.request(
2304
+ "GET",
2305
+ `${API_PREFIX}/installations/${installation.installationId}/repositories`
2306
+ );
2307
+ for (const repository of page.repositories) repositories.set(repository.id, repository);
2308
+ }
2309
+ return [...repositories.values()];
2310
+ }
2311
+ async #pollRepository(repositoryId) {
2312
+ const key = String(repositoryId);
2313
+ if (!this.#settings.repositories[key]) {
2314
+ this.#settings.repositories[key] = { afterTimestamp: this.#startedAt };
2315
+ await this.#saveSettings();
2316
+ }
2317
+ while (this.#running && this.#hasLease) {
2318
+ const cursor = this.#settings.repositories[key];
2319
+ const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE) });
2320
+ if ("afterEventId" in cursor) query.set("afterEventId", cursor.afterEventId);
2321
+ else query.set("afterTimestamp", String(cursor.afterTimestamp));
2322
+ const page = await this.#client.request(
2323
+ "GET",
2324
+ `${API_PREFIX}/repositories/${repositoryId}/events?${query}`
2325
+ );
2326
+ if (page.events.length === 0 || !page.nextCursor) return;
2327
+ for (const event of page.events) {
2328
+ if (!this.#running || !this.#hasLease) return;
2329
+ const parsed = parseEvent(event);
2330
+ if (!parsed) {
2331
+ this.deps?.logger.warn("Platform GitHub event log returned a malformed event", {
2332
+ repositoryId,
2333
+ eventId: event.id
2334
+ });
2335
+ continue;
2336
+ }
2337
+ if (isFactoryClosureEvent(parsed)) {
2338
+ await this.#ingestFactoryEvent?.(parsed);
2339
+ }
2340
+ const result = await this.#dispatch(parsed, {
2341
+ controller: this.#controller,
2342
+ listSubscriptions: (target, options) => listPullRequestSubscriptionsForWebhook(target, options, this.#github.integrationStorage),
2343
+ retireSubscription: (id, status) => retirePullRequestSubscription(id, status, this.#github.integrationStorage),
2344
+ isAuthorizedSender: (notification) => this.#isAuthorizedSender(notification),
2345
+ onTargetError: (subscription, error) => {
2346
+ this.deps?.logger.error("Platform GitHub event delivery failed for a subscription", {
2347
+ subscriptionId: subscription.id,
2348
+ resourceId: subscription.resourceId,
2349
+ threadId: subscription.threadId,
2350
+ error: error instanceof Error ? error.message : String(error)
2351
+ });
2352
+ }
2353
+ });
2354
+ if (result.failed > 0) {
2355
+ throw new Error(
2356
+ `Platform GitHub event ${event.deliveryId} failed for ${result.failed} subscribed target(s).`
2357
+ );
2358
+ }
2359
+ }
2360
+ if (page.nextCursor === ("afterEventId" in cursor ? cursor.afterEventId : void 0)) return;
2361
+ this.#settings.repositories[key] = { afterEventId: page.nextCursor };
2362
+ await this.#saveSettings();
2363
+ }
2364
+ }
2365
+ async #isAuthorizedSender(notification) {
2366
+ if (!AUTHOR_GATED_KINDS2.has(notification.kind)) return true;
2367
+ const sender = notification.metadata.sender;
2368
+ const repository = notification.metadata.repository;
2369
+ if (!sender || !repository) return false;
2370
+ if (AUTHORIZED_BOTS2.has(sender)) return true;
2371
+ const abortController = new AbortController();
2372
+ const timeout = setTimeout(() => abortController.abort(), PERMISSION_CHECK_TIMEOUT_MS2);
2373
+ try {
2374
+ const permission = await this.#github.getRepositoryCollaboratorPermission(
2375
+ notification.metadata.installationId,
2376
+ repository,
2377
+ sender,
2378
+ abortController.signal
2379
+ );
2380
+ return permission !== void 0 && AUTHORIZED_PERMISSIONS2.has(permission);
2381
+ } catch {
2382
+ return false;
2383
+ } finally {
2384
+ clearTimeout(timeout);
2385
+ }
2386
+ }
2387
+ async #saveSettings() {
2388
+ await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);
2389
+ }
2390
+ #leaseKey() {
2391
+ return `${this.name}:${this.#storage.integrationId}`;
2392
+ }
2393
+ };
2394
+ function getLeaseProvider(pubsub) {
2395
+ const getProvider = pubsub.getLeaseProvider;
2396
+ if (typeof getProvider === "function") return getProvider.call(pubsub) ?? NoopLeaseProvider;
2397
+ return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;
2398
+ }
2399
+ function normalizeSettings(value) {
2400
+ if (!value || value.version !== 1 || !value.repositories || typeof value.repositories !== "object") {
2401
+ return { version: 1, repositories: {} };
2402
+ }
2403
+ return { version: 1, repositories: { ...value.repositories } };
2404
+ }
2405
+ function isFactoryClosureEvent(event) {
2406
+ return (event.event === "issues" || event.event === "pull_request") && event.payload.action === "closed";
2407
+ }
2408
+ function parseEvent(event) {
2409
+ if (!event.id || !event.deliveryId || !SUPPORTED_EVENTS.has(event.event) || !event.payload || typeof event.payload !== "object" || Array.isArray(event.payload)) {
2410
+ return null;
2411
+ }
2412
+ return {
2413
+ event: event.event,
2414
+ deliveryId: event.deliveryId,
2415
+ payload: event.payload
2416
+ };
2417
+ }
2418
+ function retryDelay(error, fallbackMs) {
2419
+ if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {
2420
+ return Math.max(fallbackMs, error.retryAfterSeconds * 1e3);
2421
+ }
2422
+ return fallbackMs;
2423
+ }
2424
+
2425
+ // src/integrations/platform/github/integration.ts
2426
+ var PAGE_SIZE = 30;
2427
+ var API_PREFIX2 = "/v1/server";
2428
+ function loose2(c) {
2429
+ return c;
2430
+ }
2431
+ function routeBaseUrl(ctx, requestUrl) {
2432
+ return (ctx.baseUrl || new URL(requestUrl).origin).replace(/\/+$/, "");
2433
+ }
2434
+ var PlatformGithubIntegration = class {
2435
+ id = "github";
2436
+ #client;
2437
+ #endpointHost;
2438
+ #pollingEnabled;
2439
+ #pollingIntervalMs;
2440
+ #storage;
2441
+ #integrationStorage;
2442
+ intake = {
2443
+ listSources: async ({ orgId, userId }) => {
2444
+ const installations = await this.#client.request("GET", `${API_PREFIX2}/github-app/installations`);
2445
+ const usable = installations.installations.filter(
2446
+ (installation) => installation.usable && !installation.suspendedAt
2447
+ );
2448
+ const repositories = await Promise.all(
2449
+ usable.map(async (installation) => {
2450
+ const storedInstallation = await this.versionControl.registerInstallation({
2451
+ orgId,
2452
+ userId,
2453
+ installation: {
2454
+ externalId: String(installation.installationId),
2455
+ accountName: installation.accountLogin,
2456
+ accountType: installation.accountType
2457
+ }
2458
+ });
2459
+ const result = await this.#client.request("GET", `${API_PREFIX2}/github-app/installations/${installation.installationId}/repositories`);
2460
+ await this.versionControl.registerRepositories({
2461
+ orgId,
2462
+ installationId: storedInstallation.id,
2463
+ repositories: result.repositories.map((repository) => ({
2464
+ externalId: String(repository.id),
2465
+ slug: repository.fullName,
2466
+ defaultBranch: repository.defaultBranch,
2467
+ metadata: { private: repository.private, url: repository.htmlUrl }
2468
+ }))
2469
+ });
2470
+ return result.repositories.map((repository) => ({ repository, installation }));
2471
+ })
2472
+ );
2473
+ return repositories.flat().map(({ repository, installation }) => ({
2474
+ id: repository.fullName,
2475
+ name: repository.fullName,
2476
+ type: "repository",
2477
+ metadata: {
2478
+ installationId: installation.installationId,
2479
+ accountLogin: installation.accountLogin,
2480
+ accountType: installation.accountType,
2481
+ repositoryId: repository.id,
2482
+ defaultBranch: repository.defaultBranch,
2483
+ private: repository.private,
2484
+ url: repository.htmlUrl
2485
+ }
2486
+ }));
2487
+ },
2488
+ listItems: async ({ sourceIds, cursor }) => {
2489
+ const page = parsePositiveCursor(cursor);
2490
+ const pages = await Promise.all(
2491
+ sourceIds.map(async (sourceId) => {
2492
+ const connection = { type: "app-installation", installationId: 1 };
2493
+ const [issues, pullRequests] = await Promise.all([
2494
+ this.#listIssues(connection, sourceId, page),
2495
+ this.#listPullRequests({ connection, sourceId, includeDrafts: false, cursor: String(page) })
2496
+ ]);
2497
+ return {
2498
+ items: [
2499
+ ...issues.issues.map((issue) => ({
2500
+ source: { type: "issue", externalId: `${sourceId}:${issue.id}`, url: issue.url },
2501
+ sourceId,
2502
+ title: issue.title,
2503
+ status: issue.state ?? void 0,
2504
+ labels: issue.labels,
2505
+ assignee: issue.assignee,
2506
+ createdAt: issue.createdAt,
2507
+ updatedAt: issue.updatedAt,
2508
+ metadata: { repository: sourceId, number: Number(issue.id), author: issue.author }
2509
+ })),
2510
+ ...pullRequests.pullRequests.map((pullRequest) => ({
2511
+ source: { type: "pull-request", externalId: `${sourceId}:${pullRequest.id}`, url: pullRequest.url },
2512
+ sourceId,
2513
+ title: pullRequest.title,
2514
+ status: pullRequest.state,
2515
+ createdAt: pullRequest.createdAt,
2516
+ updatedAt: pullRequest.updatedAt,
2517
+ metadata: {
2518
+ repository: sourceId,
2519
+ number: Number(pullRequest.id),
2520
+ author: pullRequest.author,
2521
+ baseBranch: pullRequest.baseBranch,
2522
+ headBranch: pullRequest.headBranch
2523
+ }
2524
+ }))
2525
+ ],
2526
+ hasNextPage: issues.nextCursor !== null || pullRequests.nextCursor !== null
2527
+ };
2528
+ })
2529
+ );
2530
+ return {
2531
+ items: pages.flatMap((result) => result.items),
2532
+ nextCursor: pages.some((result) => result.hasNextPage) ? String(page + 1) : null
2533
+ };
2534
+ },
2535
+ listIssues: async (input) => {
2536
+ requireGithubConnection(input.connection);
2537
+ const sourceId = requireSingleSource(input.sourceIds, "GitHub Intake requires exactly one repository source.");
2538
+ return this.#listIssues(input.connection, sourceId, parsePositiveCursor(input.cursor), input.labels);
2539
+ },
2540
+ getIssue: (input) => this.#getIssue(input.connection, input.sourceId, input.issueId),
2541
+ createComment: (input) => this.#createIssueComment(input.connection, input.sourceId, input.issueId, input.body)
2542
+ };
2543
+ versionControl = {
2544
+ initialize: ({ storage }) => {
2545
+ this.#storage = storage;
2546
+ },
2547
+ registerInstallation: ({ orgId, userId, installation }) => this.storage.installations.upsert({
2548
+ orgId,
2549
+ connectedByUserId: userId,
2550
+ externalId: installation.externalId,
2551
+ accountName: installation.accountName,
2552
+ accountType: installation.accountType,
2553
+ providerMetadata: installation.metadata
2554
+ }),
2555
+ registerRepositories: ({ orgId, installationId, repositories }) => Promise.all(
2556
+ repositories.map(
2557
+ (repository) => this.storage.repositories.upsert({
2558
+ orgId,
2559
+ input: {
2560
+ installationId,
2561
+ externalId: repository.externalId,
2562
+ slug: repository.slug,
2563
+ defaultBranch: repository.defaultBranch,
2564
+ providerMetadata: repository.metadata
2565
+ }
2566
+ })
2567
+ )
2568
+ ),
2569
+ getRepositoryAccess: async ({ orgId, repositoryId }) => {
2570
+ const repository = await this.storage.repositories.get({ orgId, id: repositoryId });
2571
+ if (!repository) throw new Error("Version-control repository not found.");
2572
+ const installation = await this.storage.installations.get({ orgId, id: repository.installationId });
2573
+ if (!installation) throw new Error("Version-control installation not found.");
2574
+ const installationId = parsePositiveInteger(installation.externalId);
2575
+ if (installationId === null) throw new Error("GitHub installation id is invalid.");
2576
+ const repositoryName = splitRepository(repository.slug).repo;
2577
+ const token = await this.#client.request(
2578
+ "POST",
2579
+ `${API_PREFIX2}/github-app/installations/${installationId}/token`,
2580
+ { repositories: [repositoryName], permissions: { contents: "write" } }
2581
+ );
2582
+ return {
2583
+ cloneUrl: `https://github.com/${repository.slug}.git`,
2584
+ authorization: { scheme: "bearer", token: token.token }
2585
+ };
2586
+ },
2587
+ listPullRequests: (input) => this.#listPullRequests(input),
2588
+ getPullRequest: (input) => this.#getPullRequest(input),
2589
+ createPullRequest: (input) => this.#createPullRequest(input),
2590
+ updatePullRequest: (input) => this.#updatePullRequest(input),
2591
+ closePullRequest: (input) => this.#updatePullRequest({ ...input, state: "closed" }),
2592
+ mergePullRequest: (input) => this.#mergePullRequest(input),
2593
+ listComments: (input) => this.#listComments(input),
2594
+ createComment: (input) => this.#createComment(input),
2595
+ updateComment: (input) => this.#updateComment(input),
2596
+ deleteComment: (input) => this.#deleteComment(input),
2597
+ listReviews: (input) => this.#listReviews(input),
2598
+ getReview: (input) => this.#getReview(input),
2599
+ createReview: (input) => this.#createReview(input),
2600
+ updateReview: (input) => this.#updateReview(input),
2601
+ submitReview: (input) => this.#submitReview(input),
2602
+ dismissReview: (input) => this.#dismissReview(input),
2603
+ deletePendingReview: (input) => this.#deletePendingReview(input),
2604
+ listReviewComments: (input) => this.#listReviewComments(input),
2605
+ createReviewComment: (input) => this.#createReviewComment(input),
2606
+ updateReviewComment: (input) => this.#updateReviewComment(input),
2607
+ deleteReviewComment: (input) => this.#deleteReviewComment(input),
2608
+ listRequestedReviewers: (input) => this.#requestedReviewers("GET", input),
2609
+ requestReviewers: (input) => this.#requestedReviewers("POST", input),
2610
+ removeRequestedReviewers: (input) => this.#requestedReviewers("DELETE", input)
2611
+ };
2612
+ constructor() {
2613
+ const config = platformApiClientConfigFromEnv();
2614
+ this.#client = new PlatformApiClient(config);
2615
+ this.#endpointHost = new URL(config.baseUrl).host;
2616
+ this.#pollingEnabled = process.env.MASTRA_PLATFORM_GITHUB_POLLING_ENABLED?.trim().toLowerCase() !== "false";
2617
+ this.#pollingIntervalMs = optionalPositiveIntegerEnv("MASTRA_PLATFORM_GITHUB_POLLING_INTERVAL_MS");
2618
+ }
2619
+ get storage() {
2620
+ if (!this.#storage) throw new Error("PlatformGithubIntegration source-control storage has not been initialized.");
2621
+ return this.#storage;
2622
+ }
2623
+ get sourceControlStorage() {
2624
+ return this.storage;
2625
+ }
2626
+ get integrationStorage() {
2627
+ if (!this.#integrationStorage) {
2628
+ throw new Error("PlatformGithubIntegration generic storage has not been initialized.");
2629
+ }
2630
+ return this.#integrationStorage;
2631
+ }
2632
+ initialize({ storage }) {
2633
+ this.#integrationStorage = storage;
2634
+ logPlatformInfo("Platform GitHub integration initialized", {
2635
+ endpointHost: this.#endpointHost,
2636
+ pollingEnabled: this.#pollingEnabled,
2637
+ pollingIntervalMs: this.#pollingIntervalMs
2638
+ });
2639
+ }
2640
+ routes(ctx) {
2641
+ return [
2642
+ this.#statusRoute(ctx),
2643
+ this.#connectRoute(ctx),
2644
+ ...buildGithubRoutes({
2645
+ auth: ctx.auth,
2646
+ fleet: ctx.fleet,
2647
+ storage: ctx.factoryStorage,
2648
+ github: this,
2649
+ stateSigner: ctx.stateSigner,
2650
+ baseUrl: ctx.baseUrl,
2651
+ controller: ctx.controller,
2652
+ projects: ctx.storage.projects,
2653
+ emitAudit: ctx.hooks?.emitAudit,
2654
+ ingestFactoryEvent: ctx.hooks?.ingestGithubEvent
2655
+ }).filter(
2656
+ (route) => route.path !== "/web/github/status" && route.path !== "/web/github/webhook" && !route.path.startsWith("/auth/github/")
2657
+ )
2658
+ ];
2659
+ }
2660
+ #statusRoute(ctx) {
2661
+ return registerApiRoute2("/web/github/status", {
2662
+ method: "GET",
2663
+ requiresAuth: false,
2664
+ handler: async (c) => {
2665
+ await ctx.auth.ensureUser(loose2(c));
2666
+ const tenant = ctx.auth.tenant(loose2(c));
2667
+ if (!tenant) return c.json({ error: "unauthorized", reason: "auth_required" }, 401);
2668
+ if (!tenant.orgId) {
2669
+ return c.json({
2670
+ enabled: true,
2671
+ sandboxEnabled: ctx.fleet.enabled,
2672
+ organizationRequired: true,
2673
+ connected: false,
2674
+ installations: [],
2675
+ reason: "organization_required",
2676
+ diagnostics: this.diagnostics()
2677
+ });
2678
+ }
2679
+ const installations = await this.#syncInstallations(tenant.orgId, tenant.userId);
2680
+ return c.json({
2681
+ enabled: true,
2682
+ sandboxEnabled: ctx.fleet.enabled,
2683
+ connected: installations.length > 0,
2684
+ installations: installations.map((installation) => ({
2685
+ installationId: Number(installation.externalId),
2686
+ accountLogin: installation.accountName,
2687
+ accountType: installation.accountType
2688
+ })),
2689
+ reason: installations.length > 0 ? "ready" : "not_connected",
2690
+ diagnostics: this.diagnostics()
2691
+ });
2692
+ }
2693
+ });
2694
+ }
2695
+ #connectRoute(ctx) {
2696
+ return registerApiRoute2("/auth/github/connect", {
2697
+ method: "GET",
2698
+ requiresAuth: false,
2699
+ handler: async (c) => {
2700
+ await ctx.auth.ensureUser(loose2(c));
2701
+ const tenant = ctx.auth.tenant(loose2(c));
2702
+ if (!tenant?.orgId) return c.json({ error: "unauthorized" }, 401);
2703
+ const redirectTo = c.req.query("redirectTo") || c.req.query("return_to") || "/";
2704
+ const originator = routeBaseUrl(ctx, c.req.url);
2705
+ logPlatformInfo("Starting Platform GitHub connect flow", {
2706
+ orgId: tenant.orgId,
2707
+ redirectTo,
2708
+ originator
2709
+ });
2710
+ const query = new URLSearchParams({
2711
+ action: "install",
2712
+ redirectTo,
2713
+ originator
2714
+ });
2715
+ const { url } = await this.#client.request(
2716
+ "GET",
2717
+ `${API_PREFIX2}/github-app/install-url?${query}`
2718
+ );
2719
+ return c.redirect(url);
2720
+ }
2721
+ });
2722
+ }
2723
+ async #syncInstallations(orgId, userId) {
2724
+ const result = await this.#client.request(
2725
+ "GET",
2726
+ `${API_PREFIX2}/github-app/installations`
2727
+ );
2728
+ const usableInstallations = result.installations.filter(
2729
+ (installation) => installation.usable && !installation.suspendedAt
2730
+ );
2731
+ return Promise.all(
2732
+ usableInstallations.map(
2733
+ (installation) => this.versionControl.registerInstallation({
2734
+ orgId,
2735
+ userId,
2736
+ installation: {
2737
+ externalId: String(installation.installationId),
2738
+ accountName: installation.accountLogin,
2739
+ accountType: installation.accountType
2740
+ }
2741
+ })
2742
+ )
2743
+ );
2744
+ }
2745
+ workers(ctx) {
2746
+ if (!this.#pollingEnabled) return [];
2747
+ if (!ctx.controller) {
2748
+ throw new Error("Platform GitHub event polling requires the mounted Mastra Code controller.");
2749
+ }
2750
+ return [
2751
+ new PlatformGithubEventWorker({
2752
+ client: this.#client,
2753
+ controller: ctx.controller,
2754
+ github: this,
2755
+ storage: ctx.storage.generic,
2756
+ ingestFactoryEvent: ctx.hooks?.ingestGithubEvent,
2757
+ intervalMs: this.#pollingIntervalMs
2758
+ })
2759
+ ];
2760
+ }
2761
+ sessionTools({ requestContext }) {
2762
+ return createGithubSubscriptionTools(requestContext, this);
2763
+ }
2764
+ async postToolObserver({
2765
+ toolContext,
2766
+ requestContext
2767
+ }) {
2768
+ const pullRequestUrl = parseCreatedPullRequest(toolContext);
2769
+ if (!pullRequestUrl || !requestContext) return;
2770
+ await subscribeCurrentSessionToPullRequest(
2771
+ requestContext,
2772
+ pullRequestUrl,
2773
+ "auto-gh-pr-create",
2774
+ this
2775
+ );
2776
+ }
2777
+ diagnostics() {
2778
+ return {
2779
+ mode: "platform",
2780
+ endpointHost: this.#endpointHost,
2781
+ polling: {
2782
+ enabled: this.#pollingEnabled,
2783
+ ...this.#pollingIntervalMs === void 0 ? {} : { intervalMs: this.#pollingIntervalMs }
2784
+ }
2785
+ };
2786
+ }
2787
+ async getRepositoryCollaboratorPermission(_installationId, repoFullName, username, signal) {
2788
+ let repository;
2789
+ try {
2790
+ repository = splitRepository(repoFullName);
2791
+ } catch {
2792
+ return void 0;
2793
+ }
2794
+ try {
2795
+ const result = await this.#client.request(
2796
+ "GET",
2797
+ `${API_PREFIX2}/github/repos/${encodeURIComponent(repository.owner)}/${encodeURIComponent(repository.repo)}/collaborators/${encodeURIComponent(username)}/permission`,
2798
+ void 0,
2799
+ { signal }
2800
+ );
2801
+ return result.permission;
2802
+ } catch {
2803
+ return void 0;
2804
+ }
2805
+ }
2806
+ async listInstallationRepos(installationId) {
2807
+ const result = await this.#client.request("GET", `${API_PREFIX2}/github-app/installations/${installationId}/repositories`);
2808
+ return result.repositories.map((repository) => ({ ...repository, installationId }));
2809
+ }
2810
+ async mintInstallationToken(installationId) {
2811
+ const repositories = await this.listInstallationRepos(installationId);
2812
+ if (repositories.length === 0 || repositories.length > 10) {
2813
+ throw new Error("Platform GitHub token minting requires between one and ten installation repositories.");
2814
+ }
2815
+ const result = await this.#client.request(
2816
+ "POST",
2817
+ `${API_PREFIX2}/github-app/installations/${installationId}/token`,
2818
+ { repositories: repositories.map((repository) => repository.name), permissions: { contents: "write" } }
2819
+ );
2820
+ return result.token;
2821
+ }
2822
+ async addIssueLabels(_installationId, sourceId, issueNumber, labels) {
2823
+ const result = await this.#client.request(
2824
+ "POST",
2825
+ repositoryPath(sourceId, `issues/${issueNumber}/labels`),
2826
+ { labels }
2827
+ );
2828
+ return result.labels;
2829
+ }
2830
+ getInstallationOctokit(_installationId) {
2831
+ return {
2832
+ pulls: {
2833
+ get: async ({ owner, repo, pull_number }) => {
2834
+ const data = await this.#client.request(
2835
+ "GET",
2836
+ repositoryPath(`${owner}/${repo}`, `pulls/${pull_number}`)
2837
+ );
2838
+ return { data: { base: { repo: { id: data.base.repo.id } } } };
2839
+ }
2840
+ }
2841
+ };
2842
+ }
2843
+ async #listIssues(connection, sourceId, page, labels) {
2844
+ requireGithubConnection(connection);
2845
+ const path2 = repositoryPath(sourceId, "issues");
2846
+ const query = new URLSearchParams({ state: "open", page: String(page), per_page: String(PAGE_SIZE) });
2847
+ const normalizedLabels = normalizeLabels(labels);
2848
+ if (normalizedLabels.length > 0) query.set("label", normalizedLabels.join(","));
2849
+ const result = await this.#client.request("GET", `${path2}?${query}`);
2850
+ return {
2851
+ issues: result.issues.map((issue) => parseIntakeIssue(sourceId, issue)),
2852
+ nextCursor: result.issues.length === PAGE_SIZE ? String(page + 1) : null
2853
+ };
2854
+ }
2855
+ async #getIssue(connection, sourceId, issueId) {
2856
+ requireGithubConnection(connection);
2857
+ const repository = requireSource(sourceId, "GitHub Intake requires a repository source.");
2858
+ const issueNumber = requirePositiveId(issueId, "issue");
2859
+ try {
2860
+ const [issue, comments] = await Promise.all([
2861
+ this.#client.request("GET", repositoryPath(repository, `issues/${issueNumber}`)),
2862
+ this.#client.request(
2863
+ "GET",
2864
+ `${repositoryPath(repository, `issues/${issueNumber}/comments`)}?per_page=100`
2865
+ )
2866
+ ]);
2867
+ return parseIntakeIssueDetail(repository, issue, comments.comments);
2868
+ } catch (error) {
2869
+ if (isNotFound(error)) return null;
2870
+ throw error;
2871
+ }
2872
+ }
2873
+ async #createIssueComment(connection, sourceId, issueId, body) {
2874
+ requireGithubConnection(connection);
2875
+ const repository = requireSource(sourceId, "GitHub Intake requires a repository source.");
2876
+ const issueNumber = requirePositiveId(issueId, "issue");
2877
+ try {
2878
+ const comment = await this.#client.request(
2879
+ "POST",
2880
+ repositoryPath(repository, `issues/${issueNumber}/comments`),
2881
+ { body }
2882
+ );
2883
+ return { id: String(comment.id), url: comment.htmlUrl };
2884
+ } catch (error) {
2885
+ if (isNotFound(error)) return null;
2886
+ throw error;
2887
+ }
2888
+ }
2889
+ async #listPullRequests(input) {
2890
+ requireGithubConnection(input.connection);
2891
+ const page = parsePositiveCursor(input.cursor);
2892
+ const query = new URLSearchParams({
2893
+ state: input.state ?? "open",
2894
+ page: String(page),
2895
+ per_page: String(PAGE_SIZE)
2896
+ });
2897
+ const result = await this.#client.request(
2898
+ "GET",
2899
+ `${repositoryPath(input.sourceId, "pulls")}?${query}`
2900
+ );
2901
+ return {
2902
+ pullRequests: result.pullRequests.filter((pullRequest) => input.includeDrafts !== false || !pullRequest.draft).map(parsePullRequest2),
2903
+ nextCursor: result.pullRequests.length === PAGE_SIZE ? String(page + 1) : null
2904
+ };
2905
+ }
2906
+ async #getPullRequest(input) {
2907
+ try {
2908
+ return parsePullRequest2(
2909
+ await this.#client.request("GET", pullRequestPath(input, input.pullRequestId))
2910
+ );
2911
+ } catch (error) {
2912
+ if (isNotFound(error)) return null;
2913
+ throw error;
2914
+ }
2915
+ }
2916
+ async #createPullRequest(input) {
2917
+ requireGithubConnection(input.connection);
2918
+ const result = await this.#client.request("POST", repositoryPath(input.sourceId, "pulls"), {
2919
+ head: input.headBranch,
2920
+ base: input.baseBranch,
2921
+ title: input.title,
2922
+ body: input.body,
2923
+ draft: input.draft
2924
+ });
2925
+ return parsePullRequest2(result);
2926
+ }
2927
+ async #updatePullRequest(input) {
2928
+ const result = await this.#client.request("PATCH", pullRequestPath(input, input.pullRequestId), {
2929
+ title: input.title,
2930
+ body: input.body === null ? "" : input.body,
2931
+ base: input.baseBranch,
2932
+ state: input.state
2933
+ });
2934
+ return parsePullRequest2(result);
2935
+ }
2936
+ #mergePullRequest(input) {
2937
+ return this.#client.request(
2938
+ "PUT",
2939
+ `${pullRequestPath(input, input.pullRequestId)}/merge`,
2940
+ { commitTitle: input.commitTitle, commitMessage: input.commitMessage, method: input.method }
2941
+ );
2942
+ }
2943
+ async #listComments(input) {
2944
+ const page = parsePositiveCursor(input.cursor);
2945
+ const result = await this.#client.request(
2946
+ "GET",
2947
+ `${repositoryPath(input.sourceId, `issues/${requirePositiveId(input.pullRequestId, "pull request")}/comments`)}?page=${page}&per_page=${PAGE_SIZE}`
2948
+ );
2949
+ return {
2950
+ comments: result.comments.map(parseComment),
2951
+ nextCursor: result.comments.length === PAGE_SIZE ? String(page + 1) : null
2952
+ };
2953
+ }
2954
+ async #createComment(input) {
2955
+ const comment = await this.#client.request(
2956
+ "POST",
2957
+ repositoryPath(input.sourceId, `issues/${requirePositiveId(input.pullRequestId, "pull request")}/comments`),
2958
+ { body: input.body }
2959
+ );
2960
+ return parseComment(comment);
2961
+ }
2962
+ async #updateComment(input) {
2963
+ requireGithubConnection(input.connection);
2964
+ const comment = await this.#client.request(
2965
+ "PATCH",
2966
+ repositoryPath(input.sourceId, `issues/comments/${requirePositiveId(input.commentId, "comment")}`),
2967
+ { body: input.body }
2968
+ );
2969
+ return parseComment(comment);
2970
+ }
2971
+ async #deleteComment(input) {
2972
+ requireGithubConnection(input.connection);
2973
+ await this.#client.request(
2974
+ "DELETE",
2975
+ repositoryPath(input.sourceId, `issues/comments/${requirePositiveId(input.commentId, "comment")}`)
2976
+ );
2977
+ }
2978
+ async #listReviews(input) {
2979
+ const page = parsePositiveCursor(input.cursor);
2980
+ const result = await this.#client.request(
2981
+ "GET",
2982
+ `${pullRequestPath(input, input.pullRequestId)}/reviews?page=${page}&per_page=${PAGE_SIZE}`
2983
+ );
2984
+ return {
2985
+ reviews: result.reviews.map(parseReview),
2986
+ nextCursor: result.reviews.length === PAGE_SIZE ? String(page + 1) : null
2987
+ };
2988
+ }
2989
+ async #getReview(input) {
2990
+ try {
2991
+ return parseReview(
2992
+ await this.#client.request(
2993
+ "GET",
2994
+ `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}`
2995
+ )
2996
+ );
2997
+ } catch (error) {
2998
+ if (isNotFound(error)) return null;
2999
+ throw error;
3000
+ }
3001
+ }
3002
+ async #createReview(input) {
3003
+ const review = await this.#client.request(
3004
+ "POST",
3005
+ `${pullRequestPath(input, input.pullRequestId)}/reviews`,
3006
+ { body: input.body, commitId: input.commitId, event: input.event ? reviewEvent(input.event) : void 0 }
3007
+ );
3008
+ return parseReview(review);
3009
+ }
3010
+ async #updateReview(input) {
3011
+ const review = await this.#client.request(
3012
+ "PUT",
3013
+ `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}`,
3014
+ { body: input.body }
3015
+ );
3016
+ return parseReview(review);
3017
+ }
3018
+ async #submitReview(input) {
3019
+ const review = await this.#client.request(
3020
+ "POST",
3021
+ `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}/events`,
3022
+ { body: input.body, event: reviewEvent(input.event) }
3023
+ );
3024
+ return parseReview(review);
3025
+ }
3026
+ async #dismissReview(input) {
3027
+ const review = await this.#client.request(
3028
+ "PUT",
3029
+ `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}/dismissals`,
3030
+ { message: input.message }
3031
+ );
3032
+ return parseReview(review);
3033
+ }
3034
+ async #deletePendingReview(input) {
3035
+ await this.#client.request(
3036
+ "DELETE",
3037
+ `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, "review")}`
3038
+ );
3039
+ }
3040
+ async #listReviewComments(input) {
3041
+ const page = parsePositiveCursor(input.cursor);
3042
+ const result = await this.#client.request(
3043
+ "GET",
3044
+ `${pullRequestPath(input, input.pullRequestId)}/comments?page=${page}&per_page=${PAGE_SIZE}`
3045
+ );
3046
+ return {
3047
+ comments: result.comments.map(parseReviewComment),
3048
+ nextCursor: result.comments.length === PAGE_SIZE ? String(page + 1) : null
3049
+ };
3050
+ }
3051
+ async #createReviewComment(input) {
3052
+ let body;
3053
+ if (input.replyToId !== void 0) {
3054
+ body = { body: input.body, replyToId: requirePositiveId(input.replyToId, "review comment") };
3055
+ } else {
3056
+ if (!input.commitId || !input.path || input.line === void 0 || !input.side) {
3057
+ throw new Error("A review comment requires commitId, path, line, and side unless it is a reply.");
3058
+ }
3059
+ body = {
3060
+ body: input.body,
3061
+ commitId: input.commitId,
3062
+ path: input.path,
3063
+ line: input.line,
3064
+ side: input.side.toUpperCase(),
3065
+ startLine: input.startLine,
3066
+ startSide: input.startSide?.toUpperCase()
3067
+ };
3068
+ }
3069
+ return parseReviewComment(
3070
+ await this.#client.request(
3071
+ "POST",
3072
+ `${pullRequestPath(input, input.pullRequestId)}/comments`,
3073
+ body
3074
+ )
3075
+ );
3076
+ }
3077
+ async #updateReviewComment(input) {
3078
+ requireGithubConnection(input.connection);
3079
+ return parseReviewComment(
3080
+ await this.#client.request(
3081
+ "PATCH",
3082
+ repositoryPath(input.sourceId, `pulls/comments/${requirePositiveId(input.commentId, "review comment")}`),
3083
+ { body: input.body }
3084
+ )
3085
+ );
3086
+ }
3087
+ async #deleteReviewComment(input) {
3088
+ requireGithubConnection(input.connection);
3089
+ await this.#client.request(
3090
+ "DELETE",
3091
+ repositoryPath(input.sourceId, `pulls/comments/${requirePositiveId(input.commentId, "review comment")}`)
3092
+ );
3093
+ }
3094
+ #requestedReviewers(method, input) {
3095
+ requireGithubConnection(input.connection);
3096
+ return this.#client.request(
3097
+ method,
3098
+ `${pullRequestPath(input, input.pullRequestId)}/requested-reviewers`,
3099
+ method === "GET" ? void 0 : { users: input.users, teams: input.teams }
3100
+ );
3101
+ }
3102
+ };
3103
+ function repositoryPath(sourceId, suffix) {
3104
+ const { owner, repo } = splitRepository(sourceId);
3105
+ return `${API_PREFIX2}/github/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${suffix}`;
3106
+ }
3107
+ function pullRequestPath(input, pullRequestId) {
3108
+ requireGithubConnection(input.connection);
3109
+ return repositoryPath(input.sourceId, `pulls/${requirePositiveId(pullRequestId, "pull request")}`);
3110
+ }
3111
+ function splitRepository(sourceId) {
3112
+ const slash = sourceId.indexOf("/");
3113
+ if (slash <= 0 || slash === sourceId.length - 1) {
3114
+ throw new Error("GitHub capabilities require an owner/repository source.");
3115
+ }
3116
+ return { owner: sourceId.slice(0, slash), repo: sourceId.slice(slash + 1) };
3117
+ }
3118
+ function parseIntakeIssue(sourceId, issue) {
3119
+ return {
3120
+ id: String(issue.number),
3121
+ identifier: `#${issue.number}`,
3122
+ title: issue.title,
3123
+ url: issue.htmlUrl,
3124
+ author: issue.user?.login ?? null,
3125
+ state: issue.state,
3126
+ stateType: issue.state,
3127
+ priority: null,
3128
+ assignee: issue.assignees[0] ?? null,
3129
+ source: sourceId,
3130
+ labels: issue.labels,
3131
+ commentCount: issue.commentCount,
3132
+ createdAt: issue.createdAt,
3133
+ updatedAt: issue.updatedAt
3134
+ };
3135
+ }
3136
+ function parseIntakeIssueDetail(sourceId, issue, comments) {
3137
+ return {
3138
+ ...parseIntakeIssue(sourceId, issue),
3139
+ description: issue.body?.trim() ? issue.body : null,
3140
+ comments: comments.map((comment) => ({
3141
+ author: comment.user?.login ?? null,
3142
+ body: comment.body,
3143
+ createdAt: comment.createdAt
3144
+ }))
3145
+ };
3146
+ }
3147
+ function parsePullRequest2(pullRequest) {
3148
+ return {
3149
+ id: String(pullRequest.number),
3150
+ title: pullRequest.title,
3151
+ url: pullRequest.htmlUrl,
3152
+ author: pullRequest.user?.login ?? null,
3153
+ body: pullRequest.body?.trim() ? pullRequest.body : null,
3154
+ state: pullRequest.state,
3155
+ draft: pullRequest.draft,
3156
+ merged: pullRequest.merged,
3157
+ mergeable: pullRequest.mergeable,
3158
+ baseBranch: pullRequest.base.ref,
3159
+ headBranch: pullRequest.head.ref,
3160
+ headSha: pullRequest.head.sha,
3161
+ createdAt: pullRequest.createdAt,
3162
+ updatedAt: pullRequest.updatedAt
3163
+ };
3164
+ }
3165
+ function parseComment(comment) {
3166
+ return {
3167
+ id: String(comment.id),
3168
+ url: comment.htmlUrl,
3169
+ author: comment.user?.login ?? null,
3170
+ body: comment.body,
3171
+ createdAt: comment.createdAt,
3172
+ updatedAt: comment.updatedAt
3173
+ };
3174
+ }
3175
+ function parseReview(review) {
3176
+ const states = {
3177
+ PENDING: "pending",
3178
+ COMMENTED: "commented",
3179
+ APPROVED: "approved",
3180
+ CHANGES_REQUESTED: "changes-requested",
3181
+ DISMISSED: "dismissed"
3182
+ };
3183
+ return {
3184
+ id: String(review.id),
3185
+ url: review.htmlUrl,
3186
+ author: review.user?.login ?? null,
3187
+ body: review.body?.trim() ? review.body : null,
3188
+ state: states[review.state],
3189
+ commitId: review.commitId,
3190
+ submittedAt: review.submittedAt
3191
+ };
3192
+ }
3193
+ function parseReviewComment(comment) {
3194
+ return {
3195
+ ...parseComment(comment),
3196
+ path: comment.path,
3197
+ line: comment.line,
3198
+ side: comment.side?.toLowerCase(),
3199
+ commitId: comment.commitId,
3200
+ replyToId: comment.replyToId === null ? null : String(comment.replyToId)
3201
+ };
3202
+ }
3203
+ function requireGithubConnection(connection) {
3204
+ if (connection.type !== "app-installation" && connection.type !== "oauth") {
3205
+ throw new Error("GitHub capabilities require a GitHub connection.");
3206
+ }
3207
+ }
3208
+ function requireSingleSource(sourceIds, message) {
3209
+ if (sourceIds.length !== 1) throw new Error(message);
3210
+ return sourceIds[0];
3211
+ }
3212
+ function requireSource(sourceId, message) {
3213
+ if (!sourceId) throw new Error(message);
3214
+ return sourceId;
3215
+ }
3216
+ function normalizeLabels(labels) {
3217
+ return [...new Set((labels ?? []).map((label) => label.trim()).filter(Boolean))];
3218
+ }
3219
+ function parsePositiveCursor(cursor) {
3220
+ if (cursor === void 0) return 1;
3221
+ const parsed = parsePositiveInteger(cursor);
3222
+ if (parsed === null) throw new Error("GitHub cursor must be a positive page number.");
3223
+ return parsed;
3224
+ }
3225
+ function parsePositiveInteger(value) {
3226
+ if (!/^\d+$/.test(value)) return null;
3227
+ const parsed = Number(value);
3228
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
3229
+ }
3230
+ function optionalPositiveIntegerEnv(name) {
3231
+ const value = process.env[name]?.trim();
3232
+ if (!value) return void 0;
3233
+ const parsed = parsePositiveInteger(value);
3234
+ if (parsed === null) throw new Error(`${name} must be a positive integer.`);
3235
+ return parsed;
3236
+ }
3237
+ function requirePositiveId(value, resource) {
3238
+ const parsed = parsePositiveInteger(value);
3239
+ if (parsed === null) throw new Error(`GitHub ${resource} id must be a positive integer.`);
3240
+ return parsed;
3241
+ }
3242
+ function reviewEvent(event) {
3243
+ if (event === "approve") return "APPROVE";
3244
+ if (event === "request-changes") return "REQUEST_CHANGES";
3245
+ return "COMMENT";
3246
+ }
3247
+ function isNotFound(error) {
3248
+ return error instanceof PlatformApiError && error.status === 404;
3249
+ }
3250
+ export {
3251
+ PlatformGithubIntegration
3252
+ };
3253
+ //# sourceMappingURL=integration.js.map