@mastra/factory 0.0.0-fix-thread-subscription-multi-instance-redis-streams-20260730204150

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 (313) hide show
  1. package/CHANGELOG.md +695 -0
  2. package/LICENSE.md +30 -0
  3. package/README.md +27 -0
  4. package/dist/auth.d.ts +181 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +505 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/capabilities/connection.d.ts +9 -0
  9. package/dist/capabilities/connection.d.ts.map +1 -0
  10. package/dist/capabilities/connection.js +1 -0
  11. package/dist/capabilities/intake.d.ts +140 -0
  12. package/dist/capabilities/intake.d.ts.map +1 -0
  13. package/dist/capabilities/intake.js +1 -0
  14. package/dist/capabilities/version-control.d.ts +245 -0
  15. package/dist/capabilities/version-control.d.ts.map +1 -0
  16. package/dist/capabilities/version-control.js +1 -0
  17. package/dist/factory.d.ts +156 -0
  18. package/dist/factory.d.ts.map +1 -0
  19. package/dist/factory.js +483 -0
  20. package/dist/factory.js.map +1 -0
  21. package/dist/index.d.ts +14 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +7 -0
  24. package/dist/integrations/base.d.ts +210 -0
  25. package/dist/integrations/base.d.ts.map +1 -0
  26. package/dist/integrations/base.js +1 -0
  27. package/dist/integrations/github/config.d.ts +60 -0
  28. package/dist/integrations/github/config.d.ts.map +1 -0
  29. package/dist/integrations/github/config.js +42 -0
  30. package/dist/integrations/github/config.js.map +1 -0
  31. package/dist/integrations/github/factory-session.d.ts +12 -0
  32. package/dist/integrations/github/factory-session.d.ts.map +1 -0
  33. package/dist/integrations/github/factory-session.js +37 -0
  34. package/dist/integrations/github/factory-session.js.map +1 -0
  35. package/dist/integrations/github/integration.d.ts +191 -0
  36. package/dist/integrations/github/integration.d.ts.map +1 -0
  37. package/dist/integrations/github/integration.js +1077 -0
  38. package/dist/integrations/github/integration.js.map +1 -0
  39. package/dist/integrations/github/issue-triage.d.ts +27 -0
  40. package/dist/integrations/github/issue-triage.d.ts.map +1 -0
  41. package/dist/integrations/github/issue-triage.js +82 -0
  42. package/dist/integrations/github/issue-triage.js.map +1 -0
  43. package/dist/integrations/github/pat.d.ts +38 -0
  44. package/dist/integrations/github/pat.d.ts.map +1 -0
  45. package/dist/integrations/github/pat.js +59 -0
  46. package/dist/integrations/github/pat.js.map +1 -0
  47. package/dist/integrations/github/provenance.d.ts +27 -0
  48. package/dist/integrations/github/provenance.d.ts.map +1 -0
  49. package/dist/integrations/github/provenance.js +75 -0
  50. package/dist/integrations/github/provenance.js.map +1 -0
  51. package/dist/integrations/github/routes.d.ts +69 -0
  52. package/dist/integrations/github/routes.d.ts.map +1 -0
  53. package/dist/integrations/github/routes.js +1324 -0
  54. package/dist/integrations/github/routes.js.map +1 -0
  55. package/dist/integrations/github/rules.d.ts +78 -0
  56. package/dist/integrations/github/rules.d.ts.map +1 -0
  57. package/dist/integrations/github/rules.js +362 -0
  58. package/dist/integrations/github/rules.js.map +1 -0
  59. package/dist/integrations/github/sandbox-release.d.ts +38 -0
  60. package/dist/integrations/github/sandbox-release.d.ts.map +1 -0
  61. package/dist/integrations/github/sandbox-release.js +74 -0
  62. package/dist/integrations/github/sandbox-release.js.map +1 -0
  63. package/dist/integrations/github/sandbox.d.ts +281 -0
  64. package/dist/integrations/github/sandbox.d.ts.map +1 -0
  65. package/dist/integrations/github/sandbox.js +547 -0
  66. package/dist/integrations/github/sandbox.js.map +1 -0
  67. package/dist/integrations/github/session-subscriptions.d.ts +26 -0
  68. package/dist/integrations/github/session-subscriptions.d.ts.map +1 -0
  69. package/dist/integrations/github/session-subscriptions.js +192 -0
  70. package/dist/integrations/github/session-subscriptions.js.map +1 -0
  71. package/dist/integrations/github/subscriptions.d.ts +54 -0
  72. package/dist/integrations/github/subscriptions.d.ts.map +1 -0
  73. package/dist/integrations/github/subscriptions.js +62 -0
  74. package/dist/integrations/github/subscriptions.js.map +1 -0
  75. package/dist/integrations/github/token-refresh.d.ts +12 -0
  76. package/dist/integrations/github/token-refresh.d.ts.map +1 -0
  77. package/dist/integrations/github/token-refresh.js +24 -0
  78. package/dist/integrations/github/token-refresh.js.map +1 -0
  79. package/dist/integrations/github/webhook.d.ts +87 -0
  80. package/dist/integrations/github/webhook.d.ts.map +1 -0
  81. package/dist/integrations/github/webhook.js +397 -0
  82. package/dist/integrations/github/webhook.js.map +1 -0
  83. package/dist/integrations/linear/agent-tools.d.ts +34 -0
  84. package/dist/integrations/linear/agent-tools.d.ts.map +1 -0
  85. package/dist/integrations/linear/agent-tools.js +85 -0
  86. package/dist/integrations/linear/agent-tools.js.map +1 -0
  87. package/dist/integrations/linear/integration.d.ts +233 -0
  88. package/dist/integrations/linear/integration.d.ts.map +1 -0
  89. package/dist/integrations/linear/integration.js +672 -0
  90. package/dist/integrations/linear/integration.js.map +1 -0
  91. package/dist/integrations/linear/routes.d.ts +61 -0
  92. package/dist/integrations/linear/routes.d.ts.map +1 -0
  93. package/dist/integrations/linear/routes.js +239 -0
  94. package/dist/integrations/linear/routes.js.map +1 -0
  95. package/dist/integrations/linear/rules.d.ts +42 -0
  96. package/dist/integrations/linear/rules.d.ts.map +1 -0
  97. package/dist/integrations/linear/rules.js +133 -0
  98. package/dist/integrations/linear/rules.js.map +1 -0
  99. package/dist/integrations/linear/storage.d.ts +65 -0
  100. package/dist/integrations/linear/storage.d.ts.map +1 -0
  101. package/dist/integrations/linear/storage.js +1 -0
  102. package/dist/integrations/platform/api-client.d.ts +26 -0
  103. package/dist/integrations/platform/api-client.d.ts.map +1 -0
  104. package/dist/integrations/platform/api-client.js +156 -0
  105. package/dist/integrations/platform/api-client.js.map +1 -0
  106. package/dist/integrations/platform/github/event-worker.d.ts +49 -0
  107. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -0
  108. package/dist/integrations/platform/github/event-worker.js +348 -0
  109. package/dist/integrations/platform/github/event-worker.js.map +1 -0
  110. package/dist/integrations/platform/github/integration.d.ts +50 -0
  111. package/dist/integrations/platform/github/integration.d.ts.map +1 -0
  112. package/dist/integrations/platform/github/integration.js +961 -0
  113. package/dist/integrations/platform/github/integration.js.map +1 -0
  114. package/dist/integrations/platform/linear/integration.d.ts +46 -0
  115. package/dist/integrations/platform/linear/integration.d.ts.map +1 -0
  116. package/dist/integrations/platform/linear/integration.js +483 -0
  117. package/dist/integrations/platform/linear/integration.js.map +1 -0
  118. package/dist/integrations/workos/integration.d.ts +39 -0
  119. package/dist/integrations/workos/integration.d.ts.map +1 -0
  120. package/dist/integrations/workos/integration.js +91 -0
  121. package/dist/integrations/workos/integration.js.map +1 -0
  122. package/dist/routes/config.d.ts +235 -0
  123. package/dist/routes/config.d.ts.map +1 -0
  124. package/dist/routes/config.js +972 -0
  125. package/dist/routes/config.js.map +1 -0
  126. package/dist/routes/custom-provider-source.d.ts +52 -0
  127. package/dist/routes/custom-provider-source.d.ts.map +1 -0
  128. package/dist/routes/custom-provider-source.js +124 -0
  129. package/dist/routes/custom-provider-source.js.map +1 -0
  130. package/dist/routes/fs.d.ts +151 -0
  131. package/dist/routes/fs.d.ts.map +1 -0
  132. package/dist/routes/fs.js +708 -0
  133. package/dist/routes/fs.js.map +1 -0
  134. package/dist/routes/intake.d.ts +23 -0
  135. package/dist/routes/intake.d.ts.map +1 -0
  136. package/dist/routes/intake.js +179 -0
  137. package/dist/routes/intake.js.map +1 -0
  138. package/dist/routes/oauth.d.ts +43 -0
  139. package/dist/routes/oauth.d.ts.map +1 -0
  140. package/dist/routes/oauth.js +463 -0
  141. package/dist/routes/oauth.js.map +1 -0
  142. package/dist/routes/projects.d.ts +19 -0
  143. package/dist/routes/projects.d.ts.map +1 -0
  144. package/dist/routes/projects.js +461 -0
  145. package/dist/routes/projects.js.map +1 -0
  146. package/dist/routes/provider-credentials.d.ts +81 -0
  147. package/dist/routes/provider-credentials.d.ts.map +1 -0
  148. package/dist/routes/provider-credentials.js +86 -0
  149. package/dist/routes/provider-credentials.js.map +1 -0
  150. package/dist/routes/route.d.ts +48 -0
  151. package/dist/routes/route.d.ts.map +1 -0
  152. package/dist/routes/route.js +15 -0
  153. package/dist/routes/route.js.map +1 -0
  154. package/dist/routes/skills.d.ts +30 -0
  155. package/dist/routes/skills.d.ts.map +1 -0
  156. package/dist/routes/skills.js +168 -0
  157. package/dist/routes/skills.js.map +1 -0
  158. package/dist/routes/surface.d.ts +91 -0
  159. package/dist/routes/surface.d.ts.map +1 -0
  160. package/dist/routes/surface.js +260 -0
  161. package/dist/routes/surface.js.map +1 -0
  162. package/dist/routes/tenant-credentials.d.ts +74 -0
  163. package/dist/routes/tenant-credentials.d.ts.map +1 -0
  164. package/dist/routes/tenant-credentials.js +156 -0
  165. package/dist/routes/tenant-credentials.js.map +1 -0
  166. package/dist/routes/work-items.d.ts +40 -0
  167. package/dist/routes/work-items.d.ts.map +1 -0
  168. package/dist/routes/work-items.js +695 -0
  169. package/dist/routes/work-items.js.map +1 -0
  170. package/dist/rules/binding-context.d.ts +5 -0
  171. package/dist/rules/binding-context.d.ts.map +1 -0
  172. package/dist/rules/binding-context.js +28 -0
  173. package/dist/rules/binding-context.js.map +1 -0
  174. package/dist/rules/defaults.d.ts +9 -0
  175. package/dist/rules/defaults.d.ts.map +1 -0
  176. package/dist/rules/defaults.js +260 -0
  177. package/dist/rules/defaults.js.map +1 -0
  178. package/dist/rules/dispatcher.d.ts +42 -0
  179. package/dist/rules/dispatcher.d.ts.map +1 -0
  180. package/dist/rules/dispatcher.js +518 -0
  181. package/dist/rules/dispatcher.js.map +1 -0
  182. package/dist/rules/index.d.ts +7 -0
  183. package/dist/rules/index.d.ts.map +1 -0
  184. package/dist/rules/index.js +5 -0
  185. package/dist/rules/processor.d.ts +54 -0
  186. package/dist/rules/processor.d.ts.map +1 -0
  187. package/dist/rules/processor.js +378 -0
  188. package/dist/rules/processor.js.map +1 -0
  189. package/dist/rules/resolve.d.ts +17 -0
  190. package/dist/rules/resolve.d.ts.map +1 -0
  191. package/dist/rules/resolve.js +30 -0
  192. package/dist/rules/resolve.js.map +1 -0
  193. package/dist/rules/start-coordinator.d.ts +60 -0
  194. package/dist/rules/start-coordinator.d.ts.map +1 -0
  195. package/dist/rules/start-coordinator.js +194 -0
  196. package/dist/rules/start-coordinator.js.map +1 -0
  197. package/dist/rules/tools.d.ts +10 -0
  198. package/dist/rules/tools.d.ts.map +1 -0
  199. package/dist/rules/tools.js +58 -0
  200. package/dist/rules/tools.js.map +1 -0
  201. package/dist/rules/transition-service.d.ts +49 -0
  202. package/dist/rules/transition-service.d.ts.map +1 -0
  203. package/dist/rules/transition-service.js +232 -0
  204. package/dist/rules/transition-service.js.map +1 -0
  205. package/dist/rules/types.d.ts +234 -0
  206. package/dist/rules/types.d.ts.map +1 -0
  207. package/dist/rules/types.js +38 -0
  208. package/dist/rules/types.js.map +1 -0
  209. package/dist/rules/validation.d.ts +11 -0
  210. package/dist/rules/validation.d.ts.map +1 -0
  211. package/dist/rules/validation.js +308 -0
  212. package/dist/rules/validation.js.map +1 -0
  213. package/dist/sandbox/fleet.d.ts +222 -0
  214. package/dist/sandbox/fleet.d.ts.map +1 -0
  215. package/dist/sandbox/fleet.js +322 -0
  216. package/dist/sandbox/fleet.js.map +1 -0
  217. package/dist/sandbox/reattach.d.ts +3 -0
  218. package/dist/sandbox/reattach.d.ts.map +1 -0
  219. package/dist/sandbox/reattach.js +16 -0
  220. package/dist/sandbox/reattach.js.map +1 -0
  221. package/dist/server-error.d.ts +12 -0
  222. package/dist/server-error.d.ts.map +1 -0
  223. package/dist/server-error.js +16 -0
  224. package/dist/server-error.js.map +1 -0
  225. package/dist/skills/service.d.ts +48 -0
  226. package/dist/skills/service.d.ts.map +1 -0
  227. package/dist/skills/service.js +40 -0
  228. package/dist/skills/service.js.map +1 -0
  229. package/dist/spa-static.d.ts +33 -0
  230. package/dist/spa-static.d.ts.map +1 -0
  231. package/dist/spa-static.js +104 -0
  232. package/dist/spa-static.js.map +1 -0
  233. package/dist/state-signing.d.ts +59 -0
  234. package/dist/state-signing.d.ts.map +1 -0
  235. package/dist/state-signing.js +83 -0
  236. package/dist/state-signing.js.map +1 -0
  237. package/dist/storage/domains/audit/agent-audit.d.ts +27 -0
  238. package/dist/storage/domains/audit/agent-audit.d.ts.map +1 -0
  239. package/dist/storage/domains/audit/agent-audit.js +66 -0
  240. package/dist/storage/domains/audit/agent-audit.js.map +1 -0
  241. package/dist/storage/domains/audit/base.d.ts +140 -0
  242. package/dist/storage/domains/audit/base.d.ts.map +1 -0
  243. package/dist/storage/domains/audit/base.js +184 -0
  244. package/dist/storage/domains/audit/base.js.map +1 -0
  245. package/dist/storage/domains/audit/domain.d.ts +69 -0
  246. package/dist/storage/domains/audit/domain.d.ts.map +1 -0
  247. package/dist/storage/domains/audit/domain.js +167 -0
  248. package/dist/storage/domains/audit/domain.js.map +1 -0
  249. package/dist/storage/domains/channel-identity/base.d.ts +96 -0
  250. package/dist/storage/domains/channel-identity/base.d.ts.map +1 -0
  251. package/dist/storage/domains/channel-identity/base.js +149 -0
  252. package/dist/storage/domains/channel-identity/base.js.map +1 -0
  253. package/dist/storage/domains/credentials/base.d.ts +134 -0
  254. package/dist/storage/domains/credentials/base.d.ts.map +1 -0
  255. package/dist/storage/domains/credentials/base.js +273 -0
  256. package/dist/storage/domains/credentials/base.js.map +1 -0
  257. package/dist/storage/domains/custom-providers/base.d.ts +57 -0
  258. package/dist/storage/domains/custom-providers/base.d.ts.map +1 -0
  259. package/dist/storage/domains/custom-providers/base.js +145 -0
  260. package/dist/storage/domains/custom-providers/base.js.map +1 -0
  261. package/dist/storage/domains/intake/base.d.ts +38 -0
  262. package/dist/storage/domains/intake/base.d.ts.map +1 -0
  263. package/dist/storage/domains/intake/base.js +80 -0
  264. package/dist/storage/domains/intake/base.js.map +1 -0
  265. package/dist/storage/domains/integrations/base.d.ts +126 -0
  266. package/dist/storage/domains/integrations/base.d.ts.map +1 -0
  267. package/dist/storage/domains/integrations/base.js +317 -0
  268. package/dist/storage/domains/integrations/base.js.map +1 -0
  269. package/dist/storage/domains/memory-settings/base.d.ts +62 -0
  270. package/dist/storage/domains/memory-settings/base.d.ts.map +1 -0
  271. package/dist/storage/domains/memory-settings/base.js +126 -0
  272. package/dist/storage/domains/memory-settings/base.js.map +1 -0
  273. package/dist/storage/domains/model-packs/base.d.ts +49 -0
  274. package/dist/storage/domains/model-packs/base.d.ts.map +1 -0
  275. package/dist/storage/domains/model-packs/base.js +96 -0
  276. package/dist/storage/domains/model-packs/base.js.map +1 -0
  277. package/dist/storage/domains/projects/base.d.ts +58 -0
  278. package/dist/storage/domains/projects/base.d.ts.map +1 -0
  279. package/dist/storage/domains/projects/base.js +111 -0
  280. package/dist/storage/domains/projects/base.js.map +1 -0
  281. package/dist/storage/domains/queue-health/base.d.ts +52 -0
  282. package/dist/storage/domains/queue-health/base.d.ts.map +1 -0
  283. package/dist/storage/domains/queue-health/base.js +122 -0
  284. package/dist/storage/domains/queue-health/base.js.map +1 -0
  285. package/dist/storage/domains/source-control/base.d.ts +358 -0
  286. package/dist/storage/domains/source-control/base.d.ts.map +1 -0
  287. package/dist/storage/domains/source-control/base.js +908 -0
  288. package/dist/storage/domains/source-control/base.js.map +1 -0
  289. package/dist/storage/domains/source-control/inmemory.d.ts +175 -0
  290. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -0
  291. package/dist/storage/domains/source-control/inmemory.js +377 -0
  292. package/dist/storage/domains/source-control/inmemory.js.map +1 -0
  293. package/dist/storage/domains/work-items/base.d.ts +412 -0
  294. package/dist/storage/domains/work-items/base.d.ts.map +1 -0
  295. package/dist/storage/domains/work-items/base.js +1309 -0
  296. package/dist/storage/domains/work-items/base.js.map +1 -0
  297. package/dist/storage/domains/work-items/metrics.d.ts +101 -0
  298. package/dist/storage/domains/work-items/metrics.d.ts.map +1 -0
  299. package/dist/storage/domains/work-items/metrics.js +221 -0
  300. package/dist/storage/domains/work-items/metrics.js.map +1 -0
  301. package/dist/timing.d.ts +15 -0
  302. package/dist/timing.d.ts.map +1 -0
  303. package/dist/timing.js +34 -0
  304. package/dist/timing.js.map +1 -0
  305. package/dist/workspace.d.ts +24 -0
  306. package/dist/workspace.d.ts.map +1 -0
  307. package/dist/workspace.js +286 -0
  308. package/dist/workspace.js.map +1 -0
  309. package/factory-skills/configure-factory-rules/SKILL.md +67 -0
  310. package/factory-skills/factory-plan/SKILL.md +61 -0
  311. package/factory-skills/factory-review/SKILL.md +155 -0
  312. package/factory-skills/factory-triage/SKILL.md +77 -0
  313. package/package.json +81 -0
@@ -0,0 +1,1324 @@
1
+ import { clearGithubPat, getGithubPat, getGithubPatStatus, setGithubPat } from "./pat.js";
2
+ import { listPullRequestSubscriptionsForThread, subscribeToPullRequest } from "./subscriptions.js";
3
+ import { SandboxBudgetError } from "../../sandbox/fleet.js";
4
+ import { MaterializeError, WorktreeError, commitAll, computeWorktreePath, ensureProjectSandbox, isValidGitRef as isValidGitRef$1, materializeRepo, pushBranch, teardownProjectSandbox } from "./sandbox.js";
5
+ import { cleanReleasedSandbox } from "./sandbox-release.js";
6
+ import { getGithubFeatureDiagnostics, isGithubFeatureEnabled } from "./config.js";
7
+ import { handleGithubWebhook } from "./webhook.js";
8
+ import { registerApiRoute } from "@mastra/core/server";
9
+ import { randomUUID } from "crypto";
10
+ import { streamSSE } from "hono/streaming";
11
+ //#region src/integrations/github/routes.ts
12
+ /**
13
+ * Mastra `apiRoutes` for the GitHub App project feature.
14
+ *
15
+ * Registered alongside the other `/web/*` routes, behind the host auth gate.
16
+ * Every route additionally re-checks the authenticated user via the injected
17
+ * `RouteAuth` seam and scopes all rows by that user's stable id, so a user can
18
+ * only ever see and operate on their own installations and projects.
19
+ *
20
+ * When the feature is disabled (`isGithubFeatureEnabled()` false), `buildGithubRoutes`
21
+ * returns only `GET /web/github/status`, which reports `enabled:false`
22
+ * so the SPA can cleanly hide all GitHub UI.
23
+ */
24
+ const sessionOperationLocks = /* @__PURE__ */ new Map();
25
+ /**
26
+ * Serialize same-session mutations within one Factory process. Factory sessions
27
+ * normally issue these operations sequentially, so this lock is probably not
28
+ * necessary; keep the cheap local guard until that invariant is enforced by
29
+ * the request protocol. It intentionally does not consume a database connection.
30
+ */
31
+ function withSessionOperationLock(sessionId, fn) {
32
+ const next = (sessionOperationLocks.get(sessionId) ?? Promise.resolve()).then(fn, fn);
33
+ const tail = next.then(() => void 0, () => void 0);
34
+ sessionOperationLocks.set(sessionId, tail);
35
+ tail.then(() => {
36
+ if (sessionOperationLocks.get(sessionId) === tail) sessionOperationLocks.delete(sessionId);
37
+ });
38
+ return next;
39
+ }
40
+ /** Erase a route handler's path-parameterized context to a plain `Context`. */
41
+ function loose(c) {
42
+ return c;
43
+ }
44
+ /**
45
+ * Resolve the Factory project's default model for a triage run. Best-effort:
46
+ * a missing project or an uninitialized storage domain simply means "no
47
+ * default", never a failed run.
48
+ */
49
+ async function resolveFactoryDefaultModelId(projects, factoryProjectId) {
50
+ if (!projects || !factoryProjectId) return void 0;
51
+ try {
52
+ return (await projects.getById({ id: factoryProjectId }))?.defaultModelId ?? void 0;
53
+ } catch {
54
+ return;
55
+ }
56
+ }
57
+ function pullRequestNumberFromUrl(value, expectedRepo) {
58
+ try {
59
+ const url = new URL(value);
60
+ const match = url.pathname.match(/^\/([^/]+\/[^/]+)\/pull\/(\d+)\/?$/);
61
+ if (url.protocol !== "https:" || url.hostname !== "github.com" || match?.[1]?.toLowerCase() !== expectedRepo.toLowerCase()) return;
62
+ const number = Number(match[2]);
63
+ return Number.isInteger(number) && number > 0 ? number : void 0;
64
+ } catch {
65
+ return;
66
+ }
67
+ }
68
+ function isCanonicalGithubIssueUrl(value, repoFullName, issueNumber) {
69
+ try {
70
+ const url = new URL(value);
71
+ const [owner, repo] = repoFullName.split("/");
72
+ return url.protocol === "https:" && url.hostname === "github.com" && url.pathname === `/${owner}/${repo}/issues/${issueNumber}` && url.search === "" && url.hash === "";
73
+ } catch {
74
+ return false;
75
+ }
76
+ }
77
+ /**
78
+ * Validate a git branch/ref name against a strict whitelist. The value is later
79
+ * interpolated into a shell `git clone --branch` command, so it must never
80
+ * contain shell metacharacters. We accept only git-ref-safe characters and
81
+ * reject anything else rather than relying on shell quoting alone.
82
+ */
83
+ function isValidGitRef(value) {
84
+ return typeof value === "string" && value.length > 0 && value.length <= 255 && /^[A-Za-z0-9_./-]+$/.test(value);
85
+ }
86
+ /**
87
+ * Resolve the org-scoped tenant for a GitHub request. GitHub project features
88
+ * are org-owned, so they require both a signed-in user and a WorkOS
89
+ * organization. Returns the `(orgId, userId)` tenant (with `orgId` narrowed to a
90
+ * non-null string) or a ready-to-return error response: 401 when unauthenticated,
91
+ * 403 when the user has no organization (personal account).
92
+ *
93
+ * Resolves the session from the request cookie itself (via `auth.ensureUser`)
94
+ * instead of relying on the auth gate's context stash: on platform deploys
95
+ * custom `apiRoutes` run on an isolated sub-app context where the gate's
96
+ * `c.set(...)` is invisible. When the gate stash IS visible (local Hono
97
+ * server), `auth.ensureUser` returns the cached user and this is a no-op.
98
+ */
99
+ async function resolveOrgTenant(c, auth) {
100
+ await auth.ensureUser(c);
101
+ const tenant = auth.tenant(c);
102
+ if (!tenant) return { response: c.json({ error: "unauthorized" }, 401) };
103
+ if (!tenant.orgId) return { response: c.json({
104
+ error: "organization_required",
105
+ message: "GitHub projects require a WorkOS organization. Personal accounts cannot connect repositories."
106
+ }, 403) };
107
+ return { tenant: {
108
+ orgId: tenant.orgId,
109
+ userId: tenant.userId
110
+ } };
111
+ }
112
+ /**
113
+ * Parse a 1-based `page` query param. Missing means page 1; anything that is
114
+ * not a small positive integer is rejected (`null`).
115
+ */
116
+ function parseListPage(raw) {
117
+ if (raw === void 0) return 1;
118
+ if (!/^\d{1,5}$/.test(raw)) return null;
119
+ const page = Number(raw);
120
+ return page >= 1 ? page : null;
121
+ }
122
+ const VALID_ISSUE_LABEL_FILTERS = /* @__PURE__ */ new Set(["auto-triaged", "needs-approval"]);
123
+ function parseIssueLabelFilter(raw) {
124
+ if (raw === void 0 || raw === "") return void 0;
125
+ if (VALID_ISSUE_LABEL_FILTERS.has(raw)) return raw;
126
+ return null;
127
+ }
128
+ function parseIssueNumberParam(raw) {
129
+ if (!raw || !/^\d{1,10}$/.test(raw)) return null;
130
+ const issueNumber = Number(raw);
131
+ return Number.isSafeInteger(issueNumber) && issueNumber > 0 ? issueNumber : null;
132
+ }
133
+ function parseStringList(value) {
134
+ if (!Array.isArray(value)) return [];
135
+ return value.filter((item) => typeof item === "string" && item.length > 0);
136
+ }
137
+ async function resolveProjectRepository(args) {
138
+ const projectRepository = await args.github.sourceControlStorage.projectRepositories.get({
139
+ orgId: args.orgId,
140
+ id: args.projectRepositoryId
141
+ });
142
+ if (!projectRepository) return null;
143
+ const connection = await args.github.sourceControlStorage.connections.get({
144
+ orgId: args.orgId,
145
+ id: projectRepository.connectionId
146
+ });
147
+ if (!connection) return null;
148
+ const repository = await args.github.sourceControlStorage.repositories.get({
149
+ orgId: args.orgId,
150
+ id: projectRepository.repositoryId
151
+ });
152
+ if (!repository) return null;
153
+ const installation = await args.github.sourceControlStorage.installations.get({
154
+ orgId: args.orgId,
155
+ id: connection.installationId
156
+ });
157
+ if (!installation) return null;
158
+ return {
159
+ ...projectRepository,
160
+ connection,
161
+ installation,
162
+ repository,
163
+ factoryProjectId: connection.factoryProjectId,
164
+ defaultBranch: projectRepository.branch ?? repository.defaultBranch
165
+ };
166
+ }
167
+ function polledIssueEvent(project, issue) {
168
+ const repositoryId = Number(project.repository.externalId);
169
+ return {
170
+ event: "issues",
171
+ deliveryId: `poll:${repositoryId}:issue:${issue.number}:${issue.createdAt}`,
172
+ payload: {
173
+ action: "opened",
174
+ installation: { id: Number(project.installation.externalId) },
175
+ repository: {
176
+ id: repositoryId,
177
+ full_name: project.repository.slug
178
+ },
179
+ sender: { login: issue.author ?? "__unknown__" },
180
+ issue: {
181
+ number: issue.number,
182
+ title: issue.title,
183
+ html_url: issue.url,
184
+ created_at: issue.createdAt,
185
+ labels: issue.labels.map((name) => ({ name }))
186
+ }
187
+ }
188
+ };
189
+ }
190
+ function polledPullRequestEvent(project, pullRequest) {
191
+ const repositoryId = Number(project.repository.externalId);
192
+ return {
193
+ event: "pull_request",
194
+ deliveryId: `poll:${repositoryId}:pull-request:${pullRequest.number}:${pullRequest.createdAt}`,
195
+ payload: {
196
+ action: "opened",
197
+ installation: { id: Number(project.installation.externalId) },
198
+ repository: {
199
+ id: repositoryId,
200
+ full_name: project.repository.slug
201
+ },
202
+ sender: { login: pullRequest.author ?? "__unknown__" },
203
+ pull_request: {
204
+ number: pullRequest.number,
205
+ title: pullRequest.title,
206
+ html_url: pullRequest.url,
207
+ created_at: pullRequest.createdAt,
208
+ state: "open",
209
+ merged: false,
210
+ head: { ref: pullRequest.headBranch },
211
+ base: { ref: pullRequest.baseBranch }
212
+ }
213
+ }
214
+ };
215
+ }
216
+ async function ingestPolledEvents(events, ingestFactoryEvent) {
217
+ if (!ingestFactoryEvent) return;
218
+ const rejected = (await Promise.allSettled(events.map((event) => ingestFactoryEvent(event)))).find((result) => result.status === "rejected");
219
+ if (rejected) throw rejected.reason;
220
+ }
221
+ /**
222
+ * Build the GitHub routes as Mastra `apiRoutes`. When the feature is disabled,
223
+ * returns only the `status` route so the SPA can detect the disabled state.
224
+ */
225
+ function buildGithubRoutes(options) {
226
+ const routes = [];
227
+ const { auth, fleet, storage, github, stateSigner, emitAudit } = options;
228
+ const diagnostics = () => getGithubFeatureDiagnostics({
229
+ github,
230
+ auth,
231
+ appDbConfigured: storage !== void 0,
232
+ stateSigner,
233
+ fleet
234
+ });
235
+ routes.push(registerApiRoute("/web/github/status", {
236
+ method: "GET",
237
+ requiresAuth: false,
238
+ handler: async (c) => {
239
+ if (!isGithubFeatureEnabled({
240
+ github,
241
+ auth
242
+ }) || !github || !stateSigner) return c.json({
243
+ enabled: false,
244
+ connected: false,
245
+ installations: [],
246
+ reason: "missing_config",
247
+ diagnostics: diagnostics()
248
+ });
249
+ await auth.ensureUser(loose(c));
250
+ const tenant = auth.tenant(loose(c));
251
+ if (!tenant) return c.json({
252
+ error: "unauthorized",
253
+ reason: "auth_required"
254
+ }, 401);
255
+ if (!tenant.orgId) return c.json({
256
+ enabled: true,
257
+ sandboxEnabled: fleet.enabled,
258
+ organizationRequired: true,
259
+ connected: false,
260
+ installations: [],
261
+ reason: "organization_required",
262
+ diagnostics: diagnostics()
263
+ });
264
+ const rows = options.github ? await options.github.sourceControlStorage.installations.list({ orgId: tenant.orgId }) : [];
265
+ const connected = rows.length > 0;
266
+ return c.json({
267
+ enabled: true,
268
+ sandboxEnabled: fleet.enabled,
269
+ connected,
270
+ installations: rows.map((r) => ({
271
+ installationId: Number(r.externalId),
272
+ accountLogin: r.accountName,
273
+ accountType: r.accountType
274
+ })),
275
+ reason: connected ? "ready" : "not_connected",
276
+ diagnostics: diagnostics()
277
+ });
278
+ }
279
+ }));
280
+ if (!isGithubFeatureEnabled({
281
+ github,
282
+ auth
283
+ }) || !github || !stateSigner) return routes;
284
+ const signState = (orgId, userId) => stateSigner.sign(orgId, userId);
285
+ const verifyState = (state) => stateSigner.verify(state);
286
+ const { runIssueTriage } = options;
287
+ const runBoardIssueTriage = runIssueTriage ? async (input) => {
288
+ if (!input.resourceId || !input.projectPath) throw new Error("GitHub issue triage requires an explicit Factory project repository");
289
+ await github.addIssueLabels(input.installationId, input.repository, input.issueNumber, ["auto-triaged"]);
290
+ return runIssueTriage({
291
+ ...input,
292
+ defaultModelId: input.defaultModelId ?? await resolveFactoryDefaultModelId(options.projects, input.resourceId),
293
+ labels: input.labels.includes("auto-triaged") ? input.labels : [...input.labels, "auto-triaged"]
294
+ });
295
+ } : void 0;
296
+ routes.push(registerApiRoute("/web/github/subscriptions", {
297
+ method: "GET",
298
+ handler: async (c) => {
299
+ await auth.ensureUser(loose(c));
300
+ const tenant = auth.tenant(loose(c));
301
+ if (!tenant?.orgId) return c.json({ error: "unauthorized" }, 401);
302
+ const resourceId = c.req.query("resourceId");
303
+ const threadId = c.req.query("threadId");
304
+ const sessionScope = c.req.query("scope");
305
+ if (!resourceId || !threadId) return c.json({ error: "resourceId and threadId are required" }, 400);
306
+ const subscriptions = await listPullRequestSubscriptionsForThread({
307
+ orgId: tenant.orgId,
308
+ resourceId,
309
+ threadId,
310
+ sessionScope
311
+ }, github.integrationStorage);
312
+ return c.json({ subscriptions: subscriptions.map((subscription) => ({
313
+ id: subscription.id,
314
+ repoFullName: subscription.data.repositorySlug,
315
+ pullRequestNumber: Number(subscription.data.changeRequestId),
316
+ status: subscription.status,
317
+ url: `https://github.com/${subscription.data.repositorySlug}/pull/${subscription.data.changeRequestId}`
318
+ })) });
319
+ }
320
+ }), registerApiRoute("/web/github/webhook", {
321
+ method: "POST",
322
+ requiresAuth: false,
323
+ handler: async (c) => {
324
+ const result = await handleGithubWebhook(loose(c), {
325
+ github,
326
+ runIssueTriage: runBoardIssueTriage,
327
+ ingestFactoryEvent: options.ingestFactoryEvent,
328
+ ...options.controller ? {
329
+ controller: options.controller,
330
+ onTargetError: (subscription, error) => {
331
+ console.warn(`[GitHub Webhook] Delivery failed for subscription ${subscription.id} (${subscription.resourceId}/${subscription.threadId}).`, error);
332
+ }
333
+ } : {}
334
+ });
335
+ return c.json(result.body, result.status);
336
+ }
337
+ }));
338
+ const redirectUri = options.redirectUri ?? `${(options.baseUrl ?? "").replace(/\/$/, "")}/auth/github/callback`;
339
+ routes.push(registerApiRoute("/auth/github/connect", {
340
+ method: "GET",
341
+ requiresAuth: false,
342
+ handler: async (c) => {
343
+ const resolved = await resolveOrgTenant(loose(c), auth);
344
+ if ("response" in resolved) return resolved.response;
345
+ const state = signState(resolved.tenant.orgId, resolved.tenant.userId);
346
+ if (c.req.query("manage")) return c.redirect(github.buildInstallUrl(state));
347
+ return c.redirect(github.buildOAuthIdentifyUrl(state, redirectUri));
348
+ }
349
+ }));
350
+ routes.push(registerApiRoute("/auth/github/callback", {
351
+ method: "GET",
352
+ requiresAuth: false,
353
+ handler: async (c) => {
354
+ const resolved = await resolveOrgTenant(loose(c), auth);
355
+ if ("response" in resolved) return resolved.response;
356
+ const { orgId, userId } = resolved.tenant;
357
+ const state = c.req.query("state");
358
+ if (!state) return c.redirect(github.buildOAuthIdentifyUrl(signState(orgId, userId), redirectUri));
359
+ const stateTenant = verifyState(state);
360
+ if (!stateTenant || stateTenant.userId !== userId || stateTenant.orgId !== orgId) {
361
+ console.warn("[GitHub] Install callback rejected: state/tenant mismatch.", JSON.stringify({
362
+ stateValid: Boolean(stateTenant),
363
+ stateOrgId: stateTenant?.orgId,
364
+ stateUserId: stateTenant?.userId,
365
+ sessionOrgId: orgId,
366
+ sessionUserId: userId
367
+ }));
368
+ return c.redirect("/?github=error");
369
+ }
370
+ const code = c.req.query("code");
371
+ if (!code) return c.redirect(github.buildOAuthIdentifyUrl(signState(orgId, userId), redirectUri));
372
+ try {
373
+ const userToken = await github.exchangeOAuthCode(code, redirectUri);
374
+ const installations = await github.listUserInstallations(userToken);
375
+ if (installations.length === 0) return c.redirect(github.buildInstallUrl(signState(orgId, userId)));
376
+ for (const inst of installations) await github.sourceControlStorage.installations.upsert({
377
+ orgId,
378
+ connectedByUserId: userId,
379
+ externalId: inst.installationId.toString(),
380
+ accountName: inst.accountLogin,
381
+ accountType: inst.accountType
382
+ });
383
+ } catch (error) {
384
+ console.warn(`[GitHub] Install callback failed to persist installations for org ${orgId} / user ${userId}.`, error);
385
+ return c.redirect("/?github=error");
386
+ }
387
+ return c.redirect("/?github=connected");
388
+ }
389
+ }));
390
+ routes.push(registerApiRoute("/web/github/repos", {
391
+ method: "GET",
392
+ requiresAuth: false,
393
+ handler: async (c) => {
394
+ const resolved = await resolveOrgTenant(loose(c), auth);
395
+ if ("response" in resolved) return resolved.response;
396
+ const orgId = resolved.tenant.orgId;
397
+ const installs = await github.sourceControlStorage.installations.list({ orgId });
398
+ const query = (c.req.query("q") ?? "").toLowerCase();
399
+ const listed = await Promise.all(installs.map(async (inst) => {
400
+ try {
401
+ return {
402
+ inst,
403
+ list: await github.listInstallationRepos(Number(inst.externalId))
404
+ };
405
+ } catch (err) {
406
+ if (err.status !== 404) throw err;
407
+ console.error(`[Mastra Factory] pruning stale GitHub installation ${inst.externalId} (404 from GitHub)`);
408
+ await github.sourceControlStorage.installations.delete({
409
+ orgId,
410
+ id: inst.id
411
+ });
412
+ return {
413
+ inst,
414
+ list: []
415
+ };
416
+ }
417
+ }));
418
+ const matches = [];
419
+ const seenRepositoryIds = /* @__PURE__ */ new Set();
420
+ for (const { inst, list } of listed) for (const repo of list) {
421
+ if (query && !repo.fullName.toLowerCase().includes(query)) continue;
422
+ if (seenRepositoryIds.has(repo.id)) continue;
423
+ seenRepositoryIds.add(repo.id);
424
+ matches.push({
425
+ inst,
426
+ repo
427
+ });
428
+ }
429
+ const repos = new Array(matches.length);
430
+ const upsertConcurrency = 10;
431
+ for (let start = 0; start < matches.length; start += upsertConcurrency) await Promise.all(matches.slice(start, start + upsertConcurrency).map(async ({ inst, repo }, offset) => {
432
+ const repository = await github.sourceControlStorage.repositories.upsert({
433
+ orgId,
434
+ input: {
435
+ installationId: inst.id,
436
+ externalId: repo.id.toString(),
437
+ slug: repo.fullName,
438
+ defaultBranch: isValidGitRef(repo.defaultBranch) ? repo.defaultBranch : "main",
439
+ providerMetadata: {
440
+ private: repo.private,
441
+ owner: repo.owner
442
+ }
443
+ }
444
+ });
445
+ repos[start + offset] = {
446
+ ...repo,
447
+ installationStorageId: inst.id,
448
+ repositoryStorageId: repository.id,
449
+ sandboxProvider: fleet.provider,
450
+ sandboxWorkdir: fleet.computeWorkdir(repo.fullName)
451
+ };
452
+ }));
453
+ return c.json({ repos });
454
+ }
455
+ }));
456
+ routes.push(registerApiRoute("/web/github/projects/:id/ensure", {
457
+ method: "POST",
458
+ requiresAuth: false,
459
+ handler: async (c) => {
460
+ const resolved = await resolveOrgTenant(loose(c), auth);
461
+ if ("response" in resolved) return resolved.response;
462
+ const { orgId, userId } = resolved.tenant;
463
+ if (!fleet.enabled) return c.json({
464
+ error: "sandbox_not_configured",
465
+ message: "No sandbox provider is configured."
466
+ }, 503);
467
+ const projectRepositoryId = c.req.param("id");
468
+ if (!projectRepositoryId) return c.json({ error: "Project repository not found" }, 404);
469
+ const project = await resolveProjectRepository({
470
+ github,
471
+ orgId,
472
+ projectRepositoryId
473
+ });
474
+ if (!project) return c.json({ error: "Project repository not found" }, 404);
475
+ if ((c.req.header("accept") ?? "").includes("text/event-stream")) return streamSSE(loose(c), async (stream) => {
476
+ try {
477
+ const result = await prepareProject({
478
+ github,
479
+ fleet,
480
+ project,
481
+ userId,
482
+ onProgress: (ev) => void stream.writeSSE({
483
+ event: "progress",
484
+ data: JSON.stringify(ev)
485
+ })
486
+ });
487
+ await stream.writeSSE({
488
+ event: "done",
489
+ data: JSON.stringify(result)
490
+ });
491
+ } catch (err) {
492
+ await stream.writeSSE({
493
+ event: "error",
494
+ data: JSON.stringify(ensureErrorPayload(err).body)
495
+ });
496
+ }
497
+ });
498
+ try {
499
+ const result = await prepareProject({
500
+ github,
501
+ fleet,
502
+ project,
503
+ userId
504
+ });
505
+ return c.json(result);
506
+ } catch (err) {
507
+ const { status, body } = ensureErrorPayload(err);
508
+ return c.json(body, status);
509
+ }
510
+ }
511
+ }));
512
+ routes.push(registerApiRoute("/web/github/projects/:id/issues", {
513
+ method: "GET",
514
+ requiresAuth: false,
515
+ handler: async (c) => {
516
+ const loaded = await loadOrgProject({
517
+ github,
518
+ auth,
519
+ c: loose(c)
520
+ });
521
+ if ("response" in loaded) return loaded.response;
522
+ const page = parseListPage(c.req.query("page"));
523
+ if (page === null) return c.json({ error: "invalid_page" }, 400);
524
+ const label = parseIssueLabelFilter(c.req.query("label"));
525
+ if (label === null) return c.json({ error: "invalid_label" }, 400);
526
+ try {
527
+ const { issues, nextCursor } = await github.intake.listIssues({
528
+ connection: {
529
+ type: "app-installation",
530
+ installationId: Number(loaded.project.installation.externalId)
531
+ },
532
+ sourceIds: [loaded.project.repository.slug],
533
+ labels: label ? [label] : void 0,
534
+ cursor: String(page)
535
+ });
536
+ const responseIssues = issues.map((issue) => ({
537
+ number: Number(issue.id),
538
+ title: issue.title,
539
+ url: issue.url,
540
+ author: issue.author,
541
+ labels: issue.labels,
542
+ comments: issue.commentCount ?? 0,
543
+ createdAt: issue.createdAt,
544
+ updatedAt: issue.updatedAt
545
+ }));
546
+ await ingestPolledEvents(responseIssues.map((issue) => polledIssueEvent(loaded.project, issue)), options.ingestFactoryEvent);
547
+ return c.json({
548
+ issues: responseIssues,
549
+ nextPage: nextCursor === null ? null : Number(nextCursor)
550
+ });
551
+ } catch (err) {
552
+ return c.json({
553
+ error: "github_fetch_failed",
554
+ message: err instanceof Error ? err.message : String(err)
555
+ }, 502);
556
+ }
557
+ }
558
+ }));
559
+ routes.push(registerApiRoute("/web/github/projects/:id/issues/:number/triage", {
560
+ method: "POST",
561
+ requiresAuth: false,
562
+ handler: async (c) => {
563
+ const owned = await loadOwnedProject({
564
+ github,
565
+ auth,
566
+ fleet,
567
+ c: loose(c)
568
+ });
569
+ if ("response" in owned) return owned.response;
570
+ const { project, sandboxRow } = owned;
571
+ const issueNumber = parseIssueNumberParam(c.req.param("number"));
572
+ if (issueNumber === null) return c.json({ error: "invalid_issue_number" }, 400);
573
+ let body;
574
+ try {
575
+ body = await c.req.json();
576
+ } catch {
577
+ return c.json({ error: "Invalid JSON body" }, 400);
578
+ }
579
+ if (typeof body.title !== "string" || body.title.trim().length === 0 || body.title.length > 5e3) return c.json({ error: "invalid_title" }, 400);
580
+ if (typeof body.url !== "string" || body.url.trim().length === 0 || body.url.length > 2048 || !isCanonicalGithubIssueUrl(body.url, project.repository.slug, issueNumber)) return c.json({ error: "invalid_url" }, 400);
581
+ if (!runBoardIssueTriage) return c.json({ error: "triage_unavailable" }, 503);
582
+ const branch = `factory/issue-${issueNumber}`;
583
+ const projectPath = computeWorktreePath(sandboxRow.sandboxWorkdir, branch);
584
+ const result = await runBoardIssueTriage({
585
+ repository: project.repository.slug,
586
+ issueNumber,
587
+ issueTitle: body.title,
588
+ issueUrl: body.url,
589
+ labels: parseStringList(body.labels),
590
+ installationId: Number(project.installation.externalId),
591
+ resourceId: project.factoryProjectId,
592
+ projectPath,
593
+ branch
594
+ });
595
+ await emitAudit?.({
596
+ context: loose(c),
597
+ input: {
598
+ action: "factory.triage.started",
599
+ factoryProjectId: project.factoryProjectId,
600
+ projectRepositoryId: project.id,
601
+ targets: [{
602
+ type: "issue",
603
+ id: String(issueNumber),
604
+ name: body.title
605
+ }],
606
+ metadata: {
607
+ issueNumber,
608
+ branch,
609
+ threadId: result.threadId
610
+ }
611
+ }
612
+ });
613
+ return c.json({
614
+ ok: true,
615
+ threadId: result.threadId,
616
+ projectPath: result.projectPath ?? projectPath,
617
+ branch: result.branch ?? branch
618
+ }, 202);
619
+ }
620
+ }));
621
+ routes.push(registerApiRoute("/web/github/projects/:id/prs", {
622
+ method: "GET",
623
+ requiresAuth: false,
624
+ handler: async (c) => {
625
+ const loaded = await loadOrgProject({
626
+ github,
627
+ auth,
628
+ c: loose(c)
629
+ });
630
+ if ("response" in loaded) return loaded.response;
631
+ const page = parseListPage(c.req.query("page"));
632
+ if (page === null) return c.json({ error: "invalid_page" }, 400);
633
+ try {
634
+ const { pullRequests, nextCursor } = await github.versionControl.listPullRequests({
635
+ connection: {
636
+ type: "app-installation",
637
+ installationId: Number(loaded.project.installation.externalId)
638
+ },
639
+ sourceId: loaded.project.repository.slug,
640
+ includeDrafts: false,
641
+ cursor: String(page)
642
+ });
643
+ const responsePullRequests = pullRequests.map((pr) => ({
644
+ number: Number(pr.id),
645
+ title: pr.title,
646
+ url: pr.url,
647
+ author: pr.author,
648
+ baseBranch: pr.baseBranch,
649
+ headBranch: pr.headBranch,
650
+ createdAt: pr.createdAt,
651
+ updatedAt: pr.updatedAt
652
+ }));
653
+ await ingestPolledEvents(responsePullRequests.map((pullRequest) => polledPullRequestEvent(loaded.project, pullRequest)), options.ingestFactoryEvent);
654
+ return c.json({
655
+ pullRequests: responsePullRequests,
656
+ nextPage: nextCursor === null ? null : Number(nextCursor)
657
+ });
658
+ } catch (err) {
659
+ return c.json({
660
+ error: "github_fetch_failed",
661
+ message: err instanceof Error ? err.message : String(err)
662
+ }, 502);
663
+ }
664
+ }
665
+ }));
666
+ routes.push(registerApiRoute("/web/github/projects/:id/settings", {
667
+ method: "GET",
668
+ requiresAuth: false,
669
+ handler: async (c) => {
670
+ const loaded = await loadOrgProject({
671
+ github,
672
+ auth,
673
+ c: loose(c)
674
+ });
675
+ if ("response" in loaded) return loaded.response;
676
+ return c.json({ setupCommand: loaded.project.setupCommand });
677
+ }
678
+ }));
679
+ routes.push(registerApiRoute("/web/github/projects/:id/settings", {
680
+ method: "POST",
681
+ requiresAuth: false,
682
+ handler: async (c) => {
683
+ const loaded = await loadOrgProject({
684
+ github,
685
+ auth,
686
+ c: loose(c)
687
+ });
688
+ if ("response" in loaded) return loaded.response;
689
+ let body;
690
+ try {
691
+ body = await c.req.json();
692
+ } catch {
693
+ return c.json({ error: "Invalid JSON body" }, 400);
694
+ }
695
+ if (body.setupCommand !== null && typeof body.setupCommand !== "string") return c.json({ error: "Invalid setupCommand" }, 400);
696
+ if (typeof body.setupCommand === "string" && body.setupCommand.length > 2e3) return c.json({ error: "setupCommand too long (max 2000 characters)" }, 400);
697
+ if (typeof body.setupCommand === "string" && /[\0-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(body.setupCommand)) return c.json({ error: "setupCommand contains control characters" }, 400);
698
+ const setupCommand = typeof body.setupCommand === "string" && body.setupCommand.trim().length > 0 ? body.setupCommand.trim() : null;
699
+ await github.sourceControlStorage.projectRepositories.update({
700
+ orgId: loaded.project.installation.orgId,
701
+ id: loaded.project.id,
702
+ input: { setupCommand }
703
+ });
704
+ return c.json({ setupCommand });
705
+ }
706
+ }));
707
+ const parsePatKind = (value) => {
708
+ if (value === void 0 || value === null || value === "default") return "default";
709
+ if (value === "reviewer") return "reviewer";
710
+ return null;
711
+ };
712
+ routes.push(registerApiRoute("/web/github/pat", {
713
+ method: "GET",
714
+ requiresAuth: false,
715
+ handler: async (c) => {
716
+ const resolved = await resolveOrgTenant(loose(c), auth);
717
+ if ("response" in resolved) return resolved.response;
718
+ return c.json(await getGithubPatStatus(() => github.integrationStorage, resolved.tenant.orgId));
719
+ }
720
+ }), registerApiRoute("/web/github/pat", {
721
+ method: "POST",
722
+ requiresAuth: false,
723
+ handler: async (c) => {
724
+ const resolved = await resolveOrgTenant(loose(c), auth);
725
+ if ("response" in resolved) return resolved.response;
726
+ let body;
727
+ try {
728
+ body = await c.req.json();
729
+ } catch {
730
+ return c.json({ error: "Invalid JSON body" }, 400);
731
+ }
732
+ const kind = parsePatKind(body.kind);
733
+ if (!kind) return c.json({ error: "kind must be 'default' or 'reviewer'" }, 400);
734
+ const token = typeof body.token === "string" ? body.token.trim() : "";
735
+ if (!token) return c.json({ error: "A token is required" }, 400);
736
+ if (token.length > 500) return c.json({ error: "Token too long (max 500 characters)" }, 400);
737
+ if (/\s/.test(token)) return c.json({ error: "Token must not contain whitespace" }, 400);
738
+ await setGithubPat(github.integrationStorage, resolved.tenant.orgId, token, kind);
739
+ return c.json(await getGithubPatStatus(() => github.integrationStorage, resolved.tenant.orgId));
740
+ }
741
+ }), registerApiRoute("/web/github/pat", {
742
+ method: "DELETE",
743
+ requiresAuth: false,
744
+ handler: async (c) => {
745
+ const resolved = await resolveOrgTenant(loose(c), auth);
746
+ if ("response" in resolved) return resolved.response;
747
+ const kind = parsePatKind(c.req.query("kind"));
748
+ if (!kind) return c.json({ error: "kind must be 'default' or 'reviewer'" }, 400);
749
+ await clearGithubPat(github.integrationStorage, resolved.tenant.orgId, kind);
750
+ return c.json(await getGithubPatStatus(() => github.integrationStorage, resolved.tenant.orgId));
751
+ }
752
+ }));
753
+ routes.push(...buildProjectGitRoutes({
754
+ github,
755
+ auth,
756
+ fleet,
757
+ emitAudit
758
+ }));
759
+ return routes;
760
+ }
761
+ /**
762
+ * Load the org-owned project for a read-only GitHub API route. Unlike
763
+ * `loadOwnedProject`, this never touches sandbox state — the issues/PR list
764
+ * routes only need the repo + installation, so they work before a sandbox is
765
+ * ever provisioned.
766
+ */
767
+ async function loadOrgProject(options) {
768
+ const { github, auth, c } = options;
769
+ const resolved = await resolveOrgTenant(c, auth);
770
+ if ("response" in resolved) return { response: resolved.response };
771
+ const { orgId, userId } = resolved.tenant;
772
+ const projectRepositoryId = c.req.param("id");
773
+ if (!projectRepositoryId) return { response: c.json({ error: "Project repository not found" }, 404) };
774
+ const project = await resolveProjectRepository({
775
+ github,
776
+ orgId,
777
+ projectRepositoryId
778
+ });
779
+ if (!project) return { response: c.json({ error: "Project repository not found" }, 404) };
780
+ return {
781
+ project,
782
+ userId
783
+ };
784
+ }
785
+ /** Derive a commit/author identity from the authenticated host user. */
786
+ function identityFromUser(user) {
787
+ const u = user;
788
+ return {
789
+ name: u?.name ?? null,
790
+ email: u?.email ?? null
791
+ };
792
+ }
793
+ /**
794
+ * Resolve a live, started sandbox for the caller's per-user sandbox binding. The
795
+ * sandbox must already have been provisioned (`sandboxId` set) — the git write
796
+ * routes never clone, they operate on the existing checkout.
797
+ */
798
+ async function resolveProjectSandbox(options) {
799
+ const { fleet, sandboxRow } = options;
800
+ if (!sandboxRow.sandboxId) throw new MaterializeError("Project sandbox is not provisioned. Open the project first.", "clone-failed");
801
+ return fleet.reattachSandbox(sandboxRow.sandboxId);
802
+ }
803
+ /**
804
+ * Load (or create) the caller's per-(project,user) sandbox binding row. The
805
+ * binding inherits its workdir from the org-owned project, but `sandboxId` /
806
+ * `materializedAt` stay null until the user first opens the project.
807
+ */
808
+ async function loadOrCreateSandboxRow(github, project, userId) {
809
+ return github.sourceControlStorage.sandboxes.getOrCreate({
810
+ projectRepository: project,
811
+ userId
812
+ });
813
+ }
814
+ /**
815
+ * Provision/reattach the caller's sandbox and materialize the repo into it,
816
+ * emitting coarse progress events as each server step happens. Shared by both
817
+ * the JSON and SSE variants of the `/ensure` route. Throws on failure so the
818
+ * caller can shape the response (HTTP status vs SSE `error` event).
819
+ */
820
+ async function prepareProject(options) {
821
+ const { github, fleet, userId, onProgress } = options;
822
+ let project = options.project;
823
+ if (project.sandboxProvider !== fleet.provider) {
824
+ const sandboxWorkdir = fleet.computeWorkdir(project.repository.slug);
825
+ await github.sourceControlStorage.projectRepositories.update({
826
+ orgId: project.installation.orgId,
827
+ id: project.id,
828
+ input: {
829
+ sandboxProvider: fleet.provider,
830
+ sandboxWorkdir
831
+ }
832
+ });
833
+ project = {
834
+ ...project,
835
+ sandboxProvider: fleet.provider,
836
+ sandboxWorkdir
837
+ };
838
+ }
839
+ let sandboxRow = await loadOrCreateSandboxRow(github, project, userId);
840
+ if (sandboxRow.sandboxWorkdir !== project.sandboxWorkdir) {
841
+ await github.sourceControlStorage.sandboxes.setWorkdir({
842
+ id: sandboxRow.id,
843
+ sandboxWorkdir: project.sandboxWorkdir
844
+ });
845
+ sandboxRow = {
846
+ ...sandboxRow,
847
+ sandboxWorkdir: project.sandboxWorkdir,
848
+ materializedAt: null
849
+ };
850
+ }
851
+ const access = await github.versionControl.getRepositoryAccess({
852
+ orgId: project.installation.orgId,
853
+ repositoryId: project.repository.id
854
+ });
855
+ if (!access.authorization) throw new MaterializeError("Repository access did not include a bearer token.", "clone-failed");
856
+ const ghCliToken = await getGithubPat(() => github.integrationStorage, project.installation.orgId) ?? access.authorization.token;
857
+ const sandbox = await ensureProjectSandbox({
858
+ fleet,
859
+ row: sandboxRow,
860
+ storage: github.sourceControlStorage.sandboxes,
861
+ token: ghCliToken,
862
+ onProgress
863
+ });
864
+ const finalRow = await github.sourceControlStorage.sandboxes.getById({ id: sandboxRow.id }) ?? sandboxRow;
865
+ await materializeRepo({
866
+ row: finalRow,
867
+ repoInfo: {
868
+ repoFullName: project.repository.slug,
869
+ defaultBranch: project.defaultBranch
870
+ },
871
+ sandbox,
872
+ token: access.authorization.token,
873
+ storage: github.sourceControlStorage.sandboxes,
874
+ onProgress
875
+ });
876
+ const result = {
877
+ resourceId: project.factoryProjectId,
878
+ factoryProjectId: project.factoryProjectId,
879
+ projectRepositoryId: project.id,
880
+ sandboxId: finalRow.sandboxId,
881
+ sandboxWorkdir: finalRow.sandboxWorkdir
882
+ };
883
+ onProgress?.({
884
+ phase: "done",
885
+ message: "Workspace ready."
886
+ });
887
+ return result;
888
+ }
889
+ /** Shape an /ensure failure into an HTTP status + JSON body (also used as the SSE error payload). */
890
+ function ensureErrorPayload(err) {
891
+ if (err instanceof SandboxBudgetError) return {
892
+ status: 429,
893
+ body: {
894
+ error: err.code,
895
+ message: err.message
896
+ }
897
+ };
898
+ if (err instanceof MaterializeError) return {
899
+ status: 502,
900
+ body: {
901
+ error: err.code,
902
+ message: err.message
903
+ }
904
+ };
905
+ return {
906
+ status: 500,
907
+ body: {
908
+ error: "materialize_failed",
909
+ message: err instanceof Error ? err.message : String(err)
910
+ }
911
+ };
912
+ }
913
+ /** Map a sandbox/worktree error to an actionable HTTP response. */
914
+ function gitErrorResponse(c, err) {
915
+ if (err instanceof WorktreeError) return c.json({
916
+ error: err.code,
917
+ message: err.message
918
+ }, err.code === "invalid-branch" ? 400 : 502);
919
+ if (err instanceof MaterializeError) return c.json({
920
+ error: err.code,
921
+ message: err.message
922
+ }, 502);
923
+ return c.json({
924
+ error: "git_failed",
925
+ message: err instanceof Error ? err.message : String(err)
926
+ }, 500);
927
+ }
928
+ /**
929
+ * Load the org-owned project and the caller's per-user sandbox binding for a git
930
+ * route. Centralizes the auth + org/ownership checks every git route shares:
931
+ * the project is scoped by `(id, orgId)`, the sandbox binding by
932
+ * `(projectRepositoryId, userId)`. Returns the tenant, project, and sandbox row, or
933
+ * a ready-to-return error response.
934
+ */
935
+ async function loadOwnedProject(options) {
936
+ const { github, auth, fleet, c } = options;
937
+ const resolved = await resolveOrgTenant(c, auth);
938
+ if ("response" in resolved) return { response: resolved.response };
939
+ const { orgId, userId } = resolved.tenant;
940
+ if (!fleet.enabled) return { response: c.json({
941
+ error: "sandbox_not_configured",
942
+ message: "No sandbox provider is configured."
943
+ }, 503) };
944
+ const projectRepositoryId = c.req.param("id");
945
+ if (!projectRepositoryId) return { response: c.json({ error: "Project repository not found" }, 404) };
946
+ const project = await resolveProjectRepository({
947
+ github,
948
+ orgId,
949
+ projectRepositoryId
950
+ });
951
+ if (!project) return { response: c.json({ error: "Project repository not found" }, 404) };
952
+ return {
953
+ orgId,
954
+ userId,
955
+ project,
956
+ sandboxRow: await loadOrCreateSandboxRow(github, project, userId)
957
+ };
958
+ }
959
+ function buildProjectGitRoutes({ github, auth, fleet, emitAudit }) {
960
+ return [
961
+ registerApiRoute("/web/github/projects/:id/sessions", {
962
+ method: "GET",
963
+ requiresAuth: false,
964
+ handler: async (c) => {
965
+ const resolved = await resolveOrgTenant(loose(c), auth);
966
+ if ("response" in resolved) return resolved.response;
967
+ const { orgId, userId } = resolved.tenant;
968
+ const projectRepositoryId = c.req.param("id");
969
+ const project = projectRepositoryId ? await resolveProjectRepository({
970
+ github,
971
+ orgId,
972
+ projectRepositoryId
973
+ }) : null;
974
+ if (!project) return c.json({ error: "Project repository not found" }, 404);
975
+ const sessions = await github.sourceControlStorage.sessions.list({
976
+ projectRepositoryId: project.id,
977
+ userId
978
+ });
979
+ return c.json({ sessions });
980
+ }
981
+ }),
982
+ registerApiRoute("/web/github/projects/:id/sessions", {
983
+ method: "POST",
984
+ requiresAuth: false,
985
+ handler: async (c) => {
986
+ const resolved = await resolveOrgTenant(loose(c), auth);
987
+ if ("response" in resolved) return resolved.response;
988
+ const { orgId, userId } = resolved.tenant;
989
+ const projectRepositoryId = c.req.param("id");
990
+ const project = projectRepositoryId ? await resolveProjectRepository({
991
+ github,
992
+ orgId,
993
+ projectRepositoryId
994
+ }) : null;
995
+ if (!project) return c.json({ error: "Project repository not found" }, 404);
996
+ let body;
997
+ try {
998
+ body = await c.req.json();
999
+ } catch {
1000
+ return c.json({ error: "Invalid JSON body" }, 400);
1001
+ }
1002
+ if (!isValidGitRef$1(body.branch)) return c.json({ error: "Invalid branch" }, 400);
1003
+ const baseBranch = body.baseBranch === void 0 ? project.defaultBranch : body.baseBranch;
1004
+ if (!isValidGitRef$1(baseBranch)) return c.json({ error: "Invalid baseBranch" }, 400);
1005
+ const session = await github.sourceControlStorage.sessions.create({
1006
+ sessionId: randomUUID(),
1007
+ projectRepositoryId: project.id,
1008
+ orgId,
1009
+ userId,
1010
+ branch: body.branch,
1011
+ baseBranch
1012
+ });
1013
+ return c.json({ session });
1014
+ }
1015
+ }),
1016
+ registerApiRoute("/web/user-sessions/:sessionId", {
1017
+ method: "GET",
1018
+ requiresAuth: false,
1019
+ handler: async (c) => {
1020
+ const resolved = await resolveOrgTenant(loose(c), auth);
1021
+ if ("response" in resolved) return resolved.response;
1022
+ const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
1023
+ if (!session || session.orgId !== resolved.tenant.orgId || session.userId !== resolved.tenant.userId) return c.json({ error: "Session not found" }, 404);
1024
+ return c.json({ session });
1025
+ }
1026
+ }),
1027
+ registerApiRoute("/web/user-sessions/:sessionId", {
1028
+ method: "DELETE",
1029
+ requiresAuth: false,
1030
+ handler: async (c) => {
1031
+ const resolved = await resolveOrgTenant(loose(c), auth);
1032
+ if ("response" in resolved) return resolved.response;
1033
+ const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
1034
+ if (!session || session.orgId !== resolved.tenant.orgId || session.userId !== resolved.tenant.userId) return c.json({ error: "Session not found" }, 404);
1035
+ if (session.sandboxId && fleet.provider !== "local" && session.sandboxWorkdir) {
1036
+ await cleanReleasedSandbox({
1037
+ fleet,
1038
+ sourceControl: github.sourceControlStorage,
1039
+ orgId: session.orgId,
1040
+ projectRepositoryId: session.projectRepositoryId,
1041
+ sandboxId: session.sandboxId,
1042
+ sandboxWorkdir: session.sandboxWorkdir
1043
+ });
1044
+ await github.sourceControlStorage.sandboxPool.release({
1045
+ orgId: session.orgId,
1046
+ projectRepositoryId: session.projectRepositoryId,
1047
+ userId: session.userId,
1048
+ sandboxId: session.sandboxId,
1049
+ sandboxWorkdir: session.sandboxWorkdir
1050
+ });
1051
+ } else if (session.sandboxId) {
1052
+ let sandbox;
1053
+ try {
1054
+ sandbox = await fleet.reattachSandbox(session.sandboxId);
1055
+ } catch {}
1056
+ await fleet.teardownSandbox({
1057
+ sandboxId: session.sandboxId,
1058
+ setSandboxId: async () => {},
1059
+ clear: async () => {
1060
+ await github.sourceControlStorage.sessions.setSandbox({
1061
+ id: session.id,
1062
+ sandboxId: null,
1063
+ sandboxWorkdir: session.sandboxWorkdir ?? ""
1064
+ });
1065
+ }
1066
+ }, sandbox);
1067
+ }
1068
+ await github.sourceControlStorage.sessions.delete(session.id);
1069
+ return c.json({ removed: true });
1070
+ }
1071
+ }),
1072
+ registerApiRoute("/web/github/projects/:id/commit", {
1073
+ method: "POST",
1074
+ requiresAuth: false,
1075
+ handler: async (c) => {
1076
+ const owned = await loadOwnedProject({
1077
+ github,
1078
+ auth,
1079
+ fleet,
1080
+ c: loose(c)
1081
+ });
1082
+ if ("response" in owned) return owned.response;
1083
+ const { userId, project } = owned;
1084
+ let body;
1085
+ try {
1086
+ body = await c.req.json();
1087
+ } catch {
1088
+ return c.json({ error: "Invalid JSON body" }, 400);
1089
+ }
1090
+ if (typeof body.message !== "string" || body.message.trim().length === 0 || body.message.length > 5e3) return c.json({ error: "Invalid message" }, 400);
1091
+ const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
1092
+ if (!sessionWorkspace) return c.json({ error: "Invalid sessionId" }, 400);
1093
+ const { workdir, sandboxBinding } = sessionWorkspace;
1094
+ try {
1095
+ return await withSessionOperationLock(sessionWorkspace.session.sessionId, async () => {
1096
+ const result = await commitAll(await resolveProjectSandbox({
1097
+ fleet,
1098
+ sandboxRow: sandboxBinding
1099
+ }), workdir, body.message, identityFromUser(await auth.ensureUser(loose(c))));
1100
+ if (result.committed) await emitAudit?.({
1101
+ context: loose(c),
1102
+ input: {
1103
+ action: "factory.git.commit",
1104
+ factoryProjectId: project.factoryProjectId,
1105
+ projectRepositoryId: project.id,
1106
+ targets: [{
1107
+ type: "session",
1108
+ id: sessionWorkspace.session.sessionId
1109
+ }],
1110
+ metadata: { sessionId: sessionWorkspace.session.sessionId }
1111
+ }
1112
+ });
1113
+ return c.json({ committed: result.committed });
1114
+ });
1115
+ } catch (err) {
1116
+ return gitErrorResponse(loose(c), err);
1117
+ }
1118
+ }
1119
+ }),
1120
+ registerApiRoute("/web/github/projects/:id/push", {
1121
+ method: "POST",
1122
+ requiresAuth: false,
1123
+ handler: async (c) => {
1124
+ const owned = await loadOwnedProject({
1125
+ github,
1126
+ auth,
1127
+ fleet,
1128
+ c: loose(c)
1129
+ });
1130
+ if ("response" in owned) return owned.response;
1131
+ const { orgId, userId, project } = owned;
1132
+ let body;
1133
+ try {
1134
+ body = await c.req.json();
1135
+ } catch {
1136
+ return c.json({ error: "Invalid JSON body" }, 400);
1137
+ }
1138
+ if (!isValidGitRef$1(body.branch)) return c.json({ error: "Invalid branch" }, 400);
1139
+ const branch = body.branch;
1140
+ const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
1141
+ if (!sessionWorkspace) return c.json({ error: "Invalid sessionId" }, 400);
1142
+ const { workdir, sandboxBinding } = sessionWorkspace;
1143
+ try {
1144
+ return await withSessionOperationLock(sessionWorkspace.session.sessionId, async () => {
1145
+ const sandbox = await resolveProjectSandbox({
1146
+ fleet,
1147
+ sandboxRow: sandboxBinding
1148
+ });
1149
+ const access = await github.versionControl.getRepositoryAccess({
1150
+ orgId,
1151
+ repositoryId: project.repository.id
1152
+ });
1153
+ if (!access.authorization) throw new Error("Repository access did not include a bearer token.");
1154
+ await pushBranch(sandbox, workdir, branch, access.authorization.token, project.repository.slug);
1155
+ await emitAudit?.({
1156
+ context: loose(c),
1157
+ input: {
1158
+ action: "factory.git.push",
1159
+ factoryProjectId: project.factoryProjectId,
1160
+ projectRepositoryId: project.id,
1161
+ targets: [{
1162
+ type: "branch",
1163
+ id: branch
1164
+ }],
1165
+ metadata: {
1166
+ branch,
1167
+ sessionId: sessionWorkspace.session.sessionId
1168
+ }
1169
+ }
1170
+ });
1171
+ return c.json({
1172
+ pushed: true,
1173
+ branch
1174
+ });
1175
+ });
1176
+ } catch (err) {
1177
+ return gitErrorResponse(loose(c), err);
1178
+ }
1179
+ }
1180
+ }),
1181
+ registerApiRoute("/web/github/projects/:id/pr", {
1182
+ method: "POST",
1183
+ requiresAuth: false,
1184
+ handler: async (c) => {
1185
+ const owned = await loadOwnedProject({
1186
+ github,
1187
+ auth,
1188
+ fleet,
1189
+ c: loose(c)
1190
+ });
1191
+ if ("response" in owned) return owned.response;
1192
+ const { orgId, userId, project } = owned;
1193
+ let body;
1194
+ try {
1195
+ body = await c.req.json();
1196
+ } catch {
1197
+ return c.json({ error: "Invalid JSON body" }, 400);
1198
+ }
1199
+ if (!isValidGitRef$1(body.branch)) return c.json({ error: "Invalid branch" }, 400);
1200
+ const base = body.base === void 0 ? project.defaultBranch : body.base;
1201
+ if (!isValidGitRef$1(base)) return c.json({ error: "Invalid base" }, 400);
1202
+ if (typeof body.title !== "string" || body.title.trim().length === 0 || body.title.length > 256) return c.json({ error: "Invalid title" }, 400);
1203
+ if (body.body !== void 0 && (typeof body.body !== "string" || body.body.length > 65536)) return c.json({ error: "Invalid body" }, 400);
1204
+ const head = body.branch;
1205
+ const title = body.title;
1206
+ const prBody = body.body;
1207
+ const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
1208
+ if (!sessionWorkspace) return c.json({ error: "Invalid sessionId" }, 400);
1209
+ try {
1210
+ return await withSessionOperationLock(sessionWorkspace.session.sessionId, async () => {
1211
+ const result = await github.versionControl.createPullRequest({
1212
+ connection: {
1213
+ type: "app-installation",
1214
+ installationId: Number(project.installation.externalId)
1215
+ },
1216
+ sourceId: project.repository.slug,
1217
+ baseBranch: base,
1218
+ headBranch: head,
1219
+ title,
1220
+ body: prBody,
1221
+ actingUserId: userId
1222
+ });
1223
+ await emitAudit?.({
1224
+ context: loose(c),
1225
+ input: {
1226
+ action: "factory.git.pr_opened",
1227
+ factoryProjectId: project.factoryProjectId,
1228
+ projectRepositoryId: project.id,
1229
+ targets: [{
1230
+ type: "pull_request",
1231
+ id: result.url,
1232
+ name: title
1233
+ }],
1234
+ metadata: {
1235
+ branch: head,
1236
+ base,
1237
+ url: result.url
1238
+ }
1239
+ }
1240
+ });
1241
+ const pullRequestNumber = pullRequestNumberFromUrl(result.url, project.repository.slug);
1242
+ if (pullRequestNumber) {
1243
+ const sessionId = sessionWorkspace.session.sessionId;
1244
+ await subscribeToPullRequest({
1245
+ orgId,
1246
+ installationExternalId: project.installation.externalId,
1247
+ projectRepositoryId: project.id,
1248
+ repositoryExternalId: project.repository.externalId,
1249
+ repositorySlug: project.repository.slug,
1250
+ changeRequestId: pullRequestNumber.toString(),
1251
+ sessionId,
1252
+ ownerId: userId,
1253
+ resourceId: sessionId,
1254
+ threadId: sessionId,
1255
+ source: "factory-pr-create",
1256
+ subscribedByUserId: userId
1257
+ }, github.integrationStorage).catch((error) => {
1258
+ console.warn(`[GitHub] Pull request ${result.url} was created but automatic subscription failed.`, error);
1259
+ });
1260
+ }
1261
+ return c.json({ url: result.url });
1262
+ });
1263
+ } catch (err) {
1264
+ return c.json({
1265
+ error: "github_pr_create_failed",
1266
+ message: err instanceof Error ? err.message : String(err)
1267
+ }, 502);
1268
+ }
1269
+ }
1270
+ }),
1271
+ registerApiRoute("/web/github/projects/:id/sandbox", {
1272
+ method: "DELETE",
1273
+ requiresAuth: false,
1274
+ handler: async (c) => {
1275
+ const owned = await loadOwnedProject({
1276
+ github,
1277
+ auth,
1278
+ fleet,
1279
+ c: loose(c)
1280
+ });
1281
+ if ("response" in owned) return owned.response;
1282
+ const { sandboxRow } = owned;
1283
+ if (!sandboxRow.sandboxId) return c.json({ tornDown: false });
1284
+ try {
1285
+ return await withSessionOperationLock(`sandbox:${sandboxRow.id}`, async () => {
1286
+ const sandbox = await fleet.reattachSandbox(sandboxRow.sandboxId);
1287
+ await teardownProjectSandbox({
1288
+ fleet,
1289
+ row: sandboxRow,
1290
+ storage: github.sourceControlStorage.sandboxes,
1291
+ sandbox
1292
+ });
1293
+ return c.json({ tornDown: true });
1294
+ });
1295
+ } catch (err) {
1296
+ return gitErrorResponse(loose(c), err);
1297
+ }
1298
+ }
1299
+ })
1300
+ ];
1301
+ }
1302
+ /** Resolve the materialized workspace owned by a Factory session. */
1303
+ async function resolveSessionWorkspace(github, projectId, userId, sessionId) {
1304
+ if (typeof sessionId !== "string") return;
1305
+ const session = await github.sourceControlStorage.sessions.getBySessionId(sessionId);
1306
+ if (session?.projectRepositoryId !== projectId || session.userId !== userId || !session.sandboxId || !session.sandboxWorkdir) return;
1307
+ return {
1308
+ session,
1309
+ workdir: session.sandboxWorkdir,
1310
+ sandboxBinding: {
1311
+ id: session.id,
1312
+ projectRepositoryId: session.projectRepositoryId,
1313
+ userId: session.userId,
1314
+ sandboxId: session.sandboxId,
1315
+ sandboxWorkdir: session.sandboxWorkdir,
1316
+ materializedAt: session.materializedAt,
1317
+ createdAt: session.createdAt
1318
+ }
1319
+ };
1320
+ }
1321
+ //#endregion
1322
+ export { buildGithubRoutes };
1323
+
1324
+ //# sourceMappingURL=routes.js.map