@mastra/factory 0.29.0-alpha.2 → 0.29.0-alpha.4

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 (211) hide show
  1. package/README.md +44 -5
  2. package/dist/factory.d.ts +8 -0
  3. package/dist/factory.d.ts.map +1 -1
  4. package/dist/factory.js +26 -10
  5. package/dist/factory.js.map +1 -1
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1 -2
  9. package/dist/integrations/dependabot/rules.d.ts.map +1 -1
  10. package/dist/integrations/dependabot/rules.js +1 -5
  11. package/dist/integrations/dependabot/rules.js.map +1 -1
  12. package/dist/integrations/github/commits.d.ts +0 -21
  13. package/dist/integrations/github/commits.d.ts.map +1 -1
  14. package/dist/integrations/github/commits.js +1 -24
  15. package/dist/integrations/github/commits.js.map +1 -1
  16. package/dist/integrations/github/integration.d.ts +1 -1
  17. package/dist/integrations/github/integration.d.ts.map +1 -1
  18. package/dist/integrations/github/integration.js +2 -6
  19. package/dist/integrations/github/integration.js.map +1 -1
  20. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  21. package/dist/integrations/github/reconcile-worker.js +30 -1
  22. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  23. package/dist/integrations/github/routes.d.ts +1 -11
  24. package/dist/integrations/github/routes.d.ts.map +1 -1
  25. package/dist/integrations/github/routes.js +6 -515
  26. package/dist/integrations/github/routes.js.map +1 -1
  27. package/dist/integrations/github/rules.d.ts.map +1 -1
  28. package/dist/integrations/github/rules.js +76 -13
  29. package/dist/integrations/github/rules.js.map +1 -1
  30. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  31. package/dist/integrations/github/sandbox.js +11 -2
  32. package/dist/integrations/github/sandbox.js.map +1 -1
  33. package/dist/integrations/gitlab/discovery.d.ts +1 -1
  34. package/dist/integrations/gitlab/discovery.js +1 -1
  35. package/dist/integrations/gitlab/discovery.js.map +1 -1
  36. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  37. package/dist/integrations/gitlab/integration.js +0 -1
  38. package/dist/integrations/gitlab/integration.js.map +1 -1
  39. package/dist/integrations/gitlab/routes.d.ts +0 -2
  40. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  41. package/dist/integrations/gitlab/routes.js +49 -165
  42. package/dist/integrations/gitlab/routes.js.map +1 -1
  43. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  44. package/dist/integrations/gitlab/rules.js +20 -7
  45. package/dist/integrations/gitlab/rules.js.map +1 -1
  46. package/dist/integrations/incidentio/routes.d.ts +5 -5
  47. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  48. package/dist/integrations/incidentio/routes.js +3 -59
  49. package/dist/integrations/incidentio/routes.js.map +1 -1
  50. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  51. package/dist/integrations/incidentio/rules.js +1 -5
  52. package/dist/integrations/incidentio/rules.js.map +1 -1
  53. package/dist/integrations/jira/issue-reconciler.d.ts +1 -1
  54. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  55. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  56. package/dist/integrations/jira/routes.d.ts +2 -2
  57. package/dist/integrations/jira/routes.d.ts.map +1 -1
  58. package/dist/integrations/jira/routes.js +0 -68
  59. package/dist/integrations/jira/routes.js.map +1 -1
  60. package/dist/integrations/jira/rules.d.ts.map +1 -1
  61. package/dist/integrations/jira/rules.js +1 -5
  62. package/dist/integrations/jira/rules.js.map +1 -1
  63. package/dist/integrations/linear/routes.d.ts +2 -2
  64. package/dist/integrations/linear/routes.d.ts.map +1 -1
  65. package/dist/integrations/linear/routes.js +0 -83
  66. package/dist/integrations/linear/routes.js.map +1 -1
  67. package/dist/integrations/linear/rules.d.ts.map +1 -1
  68. package/dist/integrations/linear/rules.js +12 -5
  69. package/dist/integrations/linear/rules.js.map +1 -1
  70. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  71. package/dist/integrations/platform/github/integration.js +1 -3
  72. package/dist/integrations/platform/github/integration.js.map +1 -1
  73. package/dist/integrations/platform/jira/routes.d.ts +2 -2
  74. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  75. package/dist/integrations/platform/jira/routes.js +0 -69
  76. package/dist/integrations/platform/jira/routes.js.map +1 -1
  77. package/dist/integrations/vanta/rules.d.ts.map +1 -1
  78. package/dist/integrations/vanta/rules.js +1 -5
  79. package/dist/integrations/vanta/rules.js.map +1 -1
  80. package/dist/metrics/collectors/postgres.d.ts +29 -0
  81. package/dist/metrics/collectors/postgres.d.ts.map +1 -0
  82. package/dist/metrics/collectors/postgres.js +121 -0
  83. package/dist/metrics/collectors/postgres.js.map +1 -0
  84. package/dist/metrics/collectors/probe.d.ts +22 -0
  85. package/dist/metrics/collectors/probe.d.ts.map +1 -0
  86. package/dist/metrics/collectors/probe.js +69 -0
  87. package/dist/metrics/collectors/probe.js.map +1 -0
  88. package/dist/metrics/collectors/process.d.ts +13 -0
  89. package/dist/metrics/collectors/process.d.ts.map +1 -0
  90. package/dist/metrics/collectors/process.js +85 -0
  91. package/dist/metrics/collectors/process.js.map +1 -0
  92. package/dist/metrics/collectors/redis.d.ts +29 -0
  93. package/dist/metrics/collectors/redis.d.ts.map +1 -0
  94. package/dist/metrics/collectors/redis.js +97 -0
  95. package/dist/metrics/collectors/redis.js.map +1 -0
  96. package/dist/metrics/config.d.ts +33 -0
  97. package/dist/metrics/config.d.ts.map +1 -0
  98. package/dist/metrics/config.js +65 -0
  99. package/dist/metrics/config.js.map +1 -0
  100. package/dist/metrics/index.d.ts +20 -0
  101. package/dist/metrics/index.d.ts.map +1 -0
  102. package/dist/metrics/index.js +65 -0
  103. package/dist/metrics/index.js.map +1 -0
  104. package/dist/metrics/intake.d.ts +28 -0
  105. package/dist/metrics/intake.d.ts.map +1 -0
  106. package/dist/metrics/intake.js +76 -0
  107. package/dist/metrics/intake.js.map +1 -0
  108. package/dist/metrics/metrics.d.ts +60 -0
  109. package/dist/metrics/metrics.d.ts.map +1 -0
  110. package/dist/metrics/metrics.js +182 -0
  111. package/dist/metrics/metrics.js.map +1 -0
  112. package/dist/metrics/sandbox.d.ts +35 -0
  113. package/dist/metrics/sandbox.d.ts.map +1 -0
  114. package/dist/metrics/sandbox.js +156 -0
  115. package/dist/metrics/sandbox.js.map +1 -0
  116. package/dist/packages/_internals/workspace/dist/index.js.map +1 -1
  117. package/dist/routes/automation-runs.d.ts +0 -2
  118. package/dist/routes/automation-runs.d.ts.map +1 -1
  119. package/dist/routes/automation-runs.js +2 -6
  120. package/dist/routes/automation-runs.js.map +1 -1
  121. package/dist/routes/contracts.d.ts +0 -5
  122. package/dist/routes/contracts.d.ts.map +1 -1
  123. package/dist/routes/contracts.js +2 -4
  124. package/dist/routes/contracts.js.map +1 -1
  125. package/dist/routes/fs.d.ts +10 -0
  126. package/dist/routes/fs.d.ts.map +1 -1
  127. package/dist/routes/fs.js +184 -11
  128. package/dist/routes/fs.js.map +1 -1
  129. package/dist/routes/projects.d.ts.map +1 -1
  130. package/dist/routes/projects.js +4 -17
  131. package/dist/routes/projects.js.map +1 -1
  132. package/dist/routes/source-control-sessions.d.ts +0 -3
  133. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  134. package/dist/routes/source-control-sessions.js +0 -19
  135. package/dist/routes/source-control-sessions.js.map +1 -1
  136. package/dist/routes/surface.d.ts +0 -2
  137. package/dist/routes/surface.d.ts.map +1 -1
  138. package/dist/routes/surface.js +2 -12
  139. package/dist/routes/surface.js.map +1 -1
  140. package/dist/rules/dispatcher.d.ts +1 -0
  141. package/dist/rules/dispatcher.d.ts.map +1 -1
  142. package/dist/rules/dispatcher.js +27 -13
  143. package/dist/rules/dispatcher.js.map +1 -1
  144. package/dist/rules/processor.d.ts.map +1 -1
  145. package/dist/rules/processor.js +1 -6
  146. package/dist/rules/processor.js.map +1 -1
  147. package/dist/rules/start-coordinator.d.ts +1 -0
  148. package/dist/rules/start-coordinator.d.ts.map +1 -1
  149. package/dist/rules/start-coordinator.js +2 -1
  150. package/dist/rules/start-coordinator.js.map +1 -1
  151. package/dist/rules/transition-service.d.ts.map +1 -1
  152. package/dist/rules/transition-service.js +0 -2
  153. package/dist/rules/transition-service.js.map +1 -1
  154. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  155. package/dist/sandbox/session-retirement.js +22 -14
  156. package/dist/sandbox/session-retirement.js.map +1 -1
  157. package/dist/sandbox/session-sandbox.d.ts +2 -0
  158. package/dist/sandbox/session-sandbox.d.ts.map +1 -1
  159. package/dist/sandbox/session-sandbox.js +7 -1
  160. package/dist/sandbox/session-sandbox.js.map +1 -1
  161. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  162. package/dist/storage/domains/boards/schemas.js +0 -4
  163. package/dist/storage/domains/boards/schemas.js.map +1 -1
  164. package/dist/storage/domains/intake/base.d.ts +11 -10
  165. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  166. package/dist/storage/domains/intake/base.js +30 -65
  167. package/dist/storage/domains/intake/base.js.map +1 -1
  168. package/dist/storage/domains/integrations/base.d.ts +0 -2
  169. package/dist/storage/domains/integrations/base.d.ts.map +1 -1
  170. package/dist/storage/domains/integrations/base.js +0 -6
  171. package/dist/storage/domains/integrations/base.js.map +1 -1
  172. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  173. package/dist/storage/domains/projects/base.js +0 -12
  174. package/dist/storage/domains/projects/base.js.map +1 -1
  175. package/dist/storage/domains/source-control/base.d.ts +0 -10
  176. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  177. package/dist/storage/domains/source-control/base.js +1 -19
  178. package/dist/storage/domains/source-control/base.js.map +1 -1
  179. package/dist/storage/domains/source-control/inmemory.d.ts +1 -1
  180. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  181. package/dist/storage/domains/source-control/inmemory.js +1 -6
  182. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  183. package/dist/storage/domains/work-items/base.d.ts +6 -36
  184. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  185. package/dist/storage/domains/work-items/base.js +42 -82
  186. package/dist/storage/domains/work-items/base.js.map +1 -1
  187. package/dist/storage/domains/work-items/work-item-schema.d.ts +12 -3
  188. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  189. package/dist/storage/domains/work-items/work-item-schema.js +12 -3
  190. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  191. package/dist/storage/legacy-collections.d.ts +9 -0
  192. package/dist/storage/legacy-collections.d.ts.map +1 -0
  193. package/dist/storage/legacy-collections.js +17 -0
  194. package/dist/storage/legacy-collections.js.map +1 -0
  195. package/dist/timing.d.ts +4 -1
  196. package/dist/timing.d.ts.map +1 -1
  197. package/dist/timing.js +12 -4
  198. package/dist/timing.js.map +1 -1
  199. package/dist/workspace.d.ts.map +1 -1
  200. package/dist/workspace.js +8 -4
  201. package/dist/workspace.js.map +1 -1
  202. package/factory-skills/configure-factory-rules/SKILL.md +2 -2
  203. package/package.json +10 -10
  204. package/dist/session/filesystem-capture.d.ts +0 -50
  205. package/dist/session/filesystem-capture.d.ts.map +0 -1
  206. package/dist/session/filesystem-capture.js +0 -229
  207. package/dist/session/filesystem-capture.js.map +0 -1
  208. package/dist/storage/domains/filesystem/base.d.ts +0 -30
  209. package/dist/storage/domains/filesystem/base.d.ts.map +0 -1
  210. package/dist/storage/domains/filesystem/base.js +0 -78
  211. package/dist/storage/domains/filesystem/base.js.map +0 -1
@@ -1,30 +1,16 @@
1
1
  import { loose } from "../../routes/route.js";
2
- import { canReadSessionResource, canViewSourceControlSession } from "../../routes/session-access.js";
3
- import { AUTO_TRIAGED_LABEL, NEEDS_APPROVAL_LABEL } from "../../rules/types.js";
4
2
  import { isValidGitRef } from "../../sandbox/git-ref.js";
5
3
  import { requireExec } from "../../sandbox/materialization.js";
6
4
  import { peekSessionSandbox } from "../../sandbox/session-sandbox.js";
7
- import { sanitizeSegment } from "../../sandbox/workdir.js";
8
- import { waitForPendingFilesystemCapture } from "../../session/filesystem-capture.js";
9
- import { listFactorySessionThreads, sessionMemoryResourceId } from "../../session/session-threads.js";
10
- import { normalizeSessionTitle } from "../../session/session-title.js";
11
- import { isFactoryPrincipalId } from "../../storage/domains/projects/base.js";
12
- import { listRepositoryCommits } from "./commits.js";
13
5
  import { getGithubFeatureDiagnostics, isGithubFeatureEnabled } from "./config.js";
14
6
  import { clearGithubPat, getGithubPatStatus, setGithubPat } from "./pat.js";
15
7
  import { listedPullRequestState, polledPullRequestEvent } from "./rules.js";
16
- import { reclaimDeletedSessionSandbox } from "./sandbox-release.js";
17
8
  import { MaterializeError, SetupCommandError, commitAll, pushBranch } from "./sandbox.js";
18
9
  import { listPullRequestSubscriptionsForThread, subscribeToPullRequest } from "./subscriptions.js";
19
10
  import { handleGithubWebhook } from "./webhook.js";
20
- import { RequestContext } from "@mastra/core/request-context";
21
11
  import { registerApiRoute } from "@mastra/core/server";
22
- import { UniqueViolationError } from "@mastra/core/storage";
23
- import { resolveModel } from "@mastra/code-sdk/agents/model";
24
12
  // src/integrations/github/routes.ts
25
13
  const sessionOperationLocks = /* @__PURE__ */ new Map();
26
- const USER_SESSION_BRANCH_PREFIX = "user/session-";
27
- const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
28
14
  /**
29
15
  * Serialize same-session mutations within one Factory process. Factory sessions
30
16
  * normally issue these operations sequentially, so this lock is probably not
@@ -51,9 +37,6 @@ function pullRequestNumberFromUrl(value, expectedRepo) {
51
37
  return;
52
38
  }
53
39
  }
54
- function isJsonObject(value) {
55
- return typeof value === "object" && value !== null && !Array.isArray(value);
56
- }
57
40
  /**
58
41
  * Resolve the org-scoped tenant for a GitHub request. GitHub project features
59
42
  * are org-owned, so they require both a signed-in user and a WorkOS
@@ -80,27 +63,11 @@ async function resolveOrgTenant(c, auth) {
80
63
  userId: tenant.userId
81
64
  } };
82
65
  }
83
- /**
84
- * Parse a 1-based `page` query param. Missing means page 1; anything that is
85
- * not a small positive integer is rejected (`null`).
86
- */
87
- function parseListPage(raw) {
88
- if (raw === void 0) return 1;
89
- if (!/^\d{1,5}$/.test(raw)) return null;
90
- const page = Number(raw);
91
- return page >= 1 ? page : null;
92
- }
93
66
  function parseResourceNumber(raw) {
94
67
  if (raw === void 0 || !/^\d{1,10}$/.test(raw)) return null;
95
68
  const parsed = Number(raw);
96
69
  return parsed > 0 ? parsed : null;
97
70
  }
98
- const VALID_ISSUE_LABEL_FILTERS = /* @__PURE__ */ new Set([AUTO_TRIAGED_LABEL, NEEDS_APPROVAL_LABEL]);
99
- function parseIssueLabelFilter(raw) {
100
- if (raw === void 0 || raw === "") return void 0;
101
- if (VALID_ISSUE_LABEL_FILTERS.has(raw)) return raw;
102
- return null;
103
- }
104
71
  async function resolveProjectRepository(args) {
105
72
  const projectRepository = await args.github.sourceControlStorage.projectRepositories.get({
106
73
  orgId: args.orgId,
@@ -226,7 +193,7 @@ async function ingestLinkedRepositoryBacklog(args) {
226
193
  */
227
194
  function buildGithubRoutes(options) {
228
195
  const routes = [];
229
- const { auth, sandbox, users, storage, github, stateSigner, controller, memorySettings, emitAudit, sessionRetirement, workItems } = options;
196
+ const { auth, sandbox, storage, github, stateSigner, emitAudit } = options;
230
197
  const diagnostics = () => getGithubFeatureDiagnostics({
231
198
  github,
232
199
  auth,
@@ -310,6 +277,7 @@ function buildGithubRoutes(options) {
310
277
  repoFullName: subscription.data.repositorySlug,
311
278
  pullRequestNumber: Number(subscription.data.changeRequestId),
312
279
  status: subscription.status,
280
+ updatedAt: subscription.updatedAt.toISOString(),
313
281
  url: `https://github.com/${subscription.data.repositorySlug}/pull/${subscription.data.changeRequestId}`
314
282
  })) });
315
283
  }
@@ -431,62 +399,11 @@ function buildGithubRoutes(options) {
431
399
  }
432
400
  const repos = matches.map(({ inst, repo }) => ({
433
401
  ...repo,
434
- installationStorageId: inst.id,
435
- sandboxProvider: sandbox ? "custom" : "none",
436
- sandboxWorkdir: `~/${sanitizeSegment(repo.fullName.split("/", 2)[1] || "repo")}`
402
+ installationStorageId: inst.id
437
403
  }));
438
404
  return c.json({ repos });
439
405
  }
440
406
  }));
441
- routes.push(registerApiRoute("/web/github/projects/:id/issues", {
442
- method: "GET",
443
- requiresAuth: false,
444
- handler: async (c) => {
445
- const loaded = await loadOrgProject({
446
- github,
447
- auth,
448
- c: loose(c)
449
- });
450
- if ("response" in loaded) return loaded.response;
451
- const page = parseListPage(c.req.query("page"));
452
- if (page === null) return c.json({ error: "invalid_page" }, 400);
453
- const label = parseIssueLabelFilter(c.req.query("label"));
454
- if (label === null) return c.json({ error: "invalid_label" }, 400);
455
- try {
456
- const { issues, nextCursor } = await github.intake.listIssues({
457
- connection: {
458
- type: "app-installation",
459
- installationId: Number(loaded.project.installation.externalId)
460
- },
461
- sourceIds: [loaded.project.repository.slug],
462
- labels: label ? [label] : void 0,
463
- cursor: String(page)
464
- });
465
- const responseIssues = issues.map((issue) => ({
466
- repositoryId: Number(loaded.project.repository.externalId),
467
- number: Number(issue.id),
468
- title: issue.title,
469
- url: issue.url,
470
- author: issue.author,
471
- assignee: issue.assignee,
472
- assignees: issue.assignees,
473
- labels: issue.labels,
474
- comments: issue.commentCount ?? 0,
475
- createdAt: issue.createdAt,
476
- updatedAt: issue.updatedAt
477
- }));
478
- return c.json({
479
- issues: responseIssues,
480
- nextPage: nextCursor === null ? null : Number(nextCursor)
481
- });
482
- } catch (err) {
483
- return c.json({
484
- error: "github_fetch_failed",
485
- message: err instanceof Error ? err.message : String(err)
486
- }, 502);
487
- }
488
- }
489
- }));
490
407
  routes.push(registerApiRoute("/web/github/projects/:id/issues/:number", {
491
408
  method: "GET",
492
409
  requiresAuth: false,
@@ -529,54 +446,6 @@ function buildGithubRoutes(options) {
529
446
  }
530
447
  }
531
448
  }));
532
- routes.push(registerApiRoute("/web/github/projects/:id/prs", {
533
- method: "GET",
534
- requiresAuth: false,
535
- handler: async (c) => {
536
- const loaded = await loadOrgProject({
537
- github,
538
- auth,
539
- c: loose(c)
540
- });
541
- if ("response" in loaded) return loaded.response;
542
- const page = parseListPage(c.req.query("page"));
543
- if (page === null) return c.json({ error: "invalid_page" }, 400);
544
- try {
545
- const { pullRequests, nextCursor } = await github.versionControl.listPullRequests({
546
- connection: {
547
- type: "app-installation",
548
- installationId: Number(loaded.project.installation.externalId)
549
- },
550
- sourceId: loaded.project.repository.slug,
551
- includeDrafts: false,
552
- cursor: String(page)
553
- });
554
- const responsePullRequests = pullRequests.map((pr) => ({
555
- repositoryId: Number(loaded.project.repository.externalId),
556
- number: Number(pr.id),
557
- title: pr.title,
558
- url: pr.url,
559
- author: pr.author,
560
- assignees: pr.assignees ?? [],
561
- requestedReviewers: pr.requestedReviewers ?? [],
562
- labels: pr.labels ?? [],
563
- baseBranch: pr.baseBranch,
564
- headBranch: pr.headBranch,
565
- createdAt: pr.createdAt,
566
- updatedAt: pr.updatedAt
567
- }));
568
- return c.json({
569
- pullRequests: responsePullRequests,
570
- nextPage: nextCursor === null ? null : Number(nextCursor)
571
- });
572
- } catch (err) {
573
- return c.json({
574
- error: "github_fetch_failed",
575
- message: err instanceof Error ? err.message : String(err)
576
- }, 502);
577
- }
578
- }
579
- }));
580
449
  routes.push(registerApiRoute("/web/github/projects/:id/prs/:number", {
581
450
  method: "GET",
582
451
  requiresAuth: false,
@@ -620,65 +489,6 @@ function buildGithubRoutes(options) {
620
489
  }
621
490
  }
622
491
  }));
623
- routes.push(registerApiRoute("/web/github/projects/:id/settings", {
624
- method: "GET",
625
- requiresAuth: false,
626
- handler: async (c) => {
627
- const loaded = await loadOrgProject({
628
- github,
629
- auth,
630
- c: loose(c)
631
- });
632
- if ("response" in loaded) return loaded.response;
633
- return c.json({
634
- setupCommand: loaded.project.setupCommand,
635
- teardownCommand: loaded.project.teardownCommand
636
- });
637
- }
638
- }));
639
- routes.push(registerApiRoute("/web/github/projects/:id/settings", {
640
- method: "POST",
641
- requiresAuth: false,
642
- handler: async (c) => {
643
- const loaded = await loadOrgProject({
644
- github,
645
- auth,
646
- c: loose(c)
647
- });
648
- if ("response" in loaded) return loaded.response;
649
- let body;
650
- try {
651
- body = await c.req.json();
652
- } catch {
653
- return c.json({ error: "Invalid JSON body" }, 400);
654
- }
655
- for (const command of ["setupCommand", "teardownCommand"]) {
656
- const value = body[command];
657
- if (value === void 0) continue;
658
- if (value !== null && typeof value !== "string") return c.json({ error: `Invalid ${command}` }, 400);
659
- if (typeof value === "string" && value.length > 2e3) return c.json({ error: `${command} too long (max 2000 characters)` }, 400);
660
- if (typeof value === "string" && /[\0-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value)) return c.json({ error: `${command} contains control characters` }, 400);
661
- }
662
- const normalizeCommand = (value) => {
663
- if (value === void 0) return void 0;
664
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
665
- };
666
- const setupCommand = normalizeCommand(body.setupCommand);
667
- const teardownCommand = normalizeCommand(body.teardownCommand);
668
- await github.sourceControlStorage.projectRepositories.update({
669
- orgId: loaded.project.installation.orgId,
670
- id: loaded.project.id,
671
- input: {
672
- ...setupCommand !== void 0 ? { setupCommand } : {},
673
- ...teardownCommand !== void 0 ? { teardownCommand } : {}
674
- }
675
- });
676
- return c.json({
677
- setupCommand: setupCommand === void 0 ? loaded.project.setupCommand : setupCommand,
678
- teardownCommand: teardownCommand === void 0 ? loaded.project.teardownCommand : teardownCommand
679
- });
680
- }
681
- }));
682
492
  const parsePatKind = (value) => {
683
493
  if (value === void 0 || value === null || value === "default") return "default";
684
494
  if (value === "reviewer") return "reviewer";
@@ -729,18 +539,13 @@ function buildGithubRoutes(options) {
729
539
  github,
730
540
  auth,
731
541
  sandbox,
732
- users,
733
- controller,
734
- memorySettings,
735
- emitAudit,
736
- sessionRetirement,
737
- workItems
542
+ emitAudit
738
543
  }));
739
544
  return routes;
740
545
  }
741
546
  /**
742
547
  * Load the org-owned project for a read-only GitHub API route. Unlike
743
- * `loadOwnedProject`, this never touches sandbox state — the issues/PR list
548
+ * `loadOwnedProject`, this never touches sandbox state — the issue/PR detail
744
549
  * routes only need the repo + installation, so they work before a sandbox is
745
550
  * ever provisioned.
746
551
  */
@@ -815,292 +620,8 @@ async function loadOwnedProject(options) {
815
620
  project
816
621
  };
817
622
  }
818
- /**
819
- * One naming per session at a time: a second caller joins the run already in
820
- * flight instead of paying for another model call and racing its rename.
821
- */
822
- function createSessionNaming() {
823
- const inFlight = /* @__PURE__ */ new Map();
824
- return (sessionId, run) => {
825
- const pending = inFlight.get(sessionId);
826
- if (pending) return pending;
827
- const started = run().finally(() => inFlight.delete(sessionId));
828
- inFlight.set(sessionId, started);
829
- return started;
830
- };
831
- }
832
- /**
833
- * Name a thread with a stored model id. Resolution has to go through
834
- * mastracode's gateway: a bare id handed to core's model router looks for a
835
- * process env key instead of the caller's stored provider credentials.
836
- */
837
- function titleModel(modelId) {
838
- return ({ requestContext }) => resolveModel(modelId, {
839
- remapForCodexOAuth: true,
840
- requestContext
841
- });
842
- }
843
- /** A screenful of history; GitHub caps its own page at 100. */
844
- const DEFAULT_COMMIT_PAGE = 20;
845
- const MAX_COMMIT_PAGE = 100;
846
- const MAX_SESSION_OWNER_PROFILES = 100;
847
- const MAX_SESSION_OWNER_PROFILE_CACHE_ENTRIES = 500;
848
- const SESSION_OWNER_PROFILE_TTL_MS = 3e5;
849
- function createSessionOwnerProfileResolver(users) {
850
- const cache = /* @__PURE__ */ new Map();
851
- const cacheProfile = (userId, profile, expiresAt) => {
852
- cache.delete(userId);
853
- cache.set(userId, {
854
- profile,
855
- expiresAt
856
- });
857
- if (cache.size > MAX_SESSION_OWNER_PROFILE_CACHE_ENTRIES) {
858
- const oldestUserId = cache.keys().next().value;
859
- if (oldestUserId !== void 0) cache.delete(oldestUserId);
860
- }
861
- };
862
- return async (userIds) => {
863
- const profiles = /* @__PURE__ */ new Map();
864
- for (const userId of userIds) if (isFactoryPrincipalId(userId)) profiles.set(userId, {
865
- id: userId,
866
- name: "Factory"
867
- });
868
- if (!users) return profiles;
869
- const requestedUserIds = [...new Set(userIds)].filter((userId) => !isFactoryPrincipalId(userId)).slice(0, MAX_SESSION_OWNER_PROFILES);
870
- const unresolvedUserIds = [];
871
- const now = Date.now();
872
- for (const userId of requestedUserIds) {
873
- const cached = cache.get(userId);
874
- if (!cached || cached.expiresAt <= now) {
875
- cache.delete(userId);
876
- unresolvedUserIds.push(userId);
877
- } else if (cached.profile) profiles.set(userId, cached.profile);
878
- }
879
- if (unresolvedUserIds.length === 0) return profiles;
880
- let resolvedUsers;
881
- if (users.getUsers) try {
882
- resolvedUsers = await users.getUsers(unresolvedUserIds);
883
- } catch (error) {
884
- console.warn("[GitHub Sessions] Bulk session owner profile lookup failed; falling back to individual lookups", { error: error instanceof Error ? error.message : String(error) });
885
- resolvedUsers = (await Promise.allSettled(unresolvedUserIds.map((userId) => users.getUser(userId)))).filter((result) => result.status === "fulfilled").map((result) => result.value);
886
- }
887
- else resolvedUsers = (await Promise.allSettled(unresolvedUserIds.map((userId) => users.getUser(userId)))).filter((result) => result.status === "fulfilled").map((result) => result.value);
888
- for (const user of resolvedUsers) {
889
- if (!user) continue;
890
- const name = user.name?.trim() || user.email?.trim();
891
- if (!name) continue;
892
- profiles.set(user.id, {
893
- id: user.id,
894
- name,
895
- ...user.avatarUrl ? { avatarUrl: user.avatarUrl } : {}
896
- });
897
- }
898
- const expiresAt = now + SESSION_OWNER_PROFILE_TTL_MS;
899
- for (const userId of unresolvedUserIds) cacheProfile(userId, profiles.get(userId), expiresAt);
900
- return profiles;
901
- };
902
- }
903
- function buildProjectGitRoutes({ github, auth, sandbox, users, controller, memorySettings, emitAudit, sessionRetirement, workItems }) {
904
- const nameSession = createSessionNaming();
905
- const resolveSessionOwnerProfiles = createSessionOwnerProfileResolver(users);
623
+ function buildProjectGitRoutes({ github, auth, sandbox, emitAudit }) {
906
624
  return [
907
- registerApiRoute("/web/github/projects/:id/sessions", {
908
- method: "GET",
909
- requiresAuth: false,
910
- handler: async (c) => {
911
- const resolved = await resolveOrgTenant(loose(c), auth);
912
- if ("response" in resolved) return resolved.response;
913
- const { orgId, userId } = resolved.tenant;
914
- const projectRepositoryId = c.req.param("id");
915
- const project = projectRepositoryId ? await resolveProjectRepository({
916
- github,
917
- orgId,
918
- projectRepositoryId
919
- }) : null;
920
- if (!project) return c.json({ error: "Project repository not found" }, 404);
921
- const sessions = await github.sourceControlStorage.sessions.list({
922
- projectRepositoryId: project.id,
923
- viewerUserId: userId
924
- });
925
- const owners = await resolveSessionOwnerProfiles(sessions.map((session) => session.userId));
926
- return c.json({ sessions: sessions.map((session) => {
927
- const owner = owners.get(session.userId);
928
- return {
929
- ...session,
930
- ...owner ? { owner } : {}
931
- };
932
- }) });
933
- }
934
- }),
935
- registerApiRoute("/web/github/projects/:id/sessions", {
936
- method: "POST",
937
- requiresAuth: false,
938
- handler: async (c) => {
939
- const resolved = await resolveOrgTenant(loose(c), auth);
940
- if ("response" in resolved) return resolved.response;
941
- const { orgId, userId } = resolved.tenant;
942
- const projectRepositoryId = c.req.param("id");
943
- const project = projectRepositoryId ? await resolveProjectRepository({
944
- github,
945
- orgId,
946
- projectRepositoryId
947
- }) : null;
948
- if (!project) return c.json({ error: "Project repository not found" }, 404);
949
- let body;
950
- try {
951
- body = await c.req.json();
952
- } catch {
953
- return c.json({ error: "Invalid JSON body" }, 400);
954
- }
955
- if (!isJsonObject(body)) return c.json({ error: "Invalid JSON body" }, 400);
956
- const requestedBaseBranch = body.baseBranch;
957
- if (requestedBaseBranch !== void 0 && typeof requestedBaseBranch !== "string") return c.json({ error: "Invalid baseBranch" }, 400);
958
- const baseBranch = requestedBaseBranch ?? project.defaultBranch;
959
- if (!isValidGitRef(baseBranch)) return c.json({ error: "Invalid baseBranch" }, 400);
960
- const requestedSessionId = body.sessionId;
961
- if (requestedSessionId !== void 0 && (typeof requestedSessionId !== "string" || !UUID_PATTERN.test(requestedSessionId))) return c.json({ error: "Invalid sessionId" }, 400);
962
- const sessionId = requestedSessionId ?? globalThis.crypto.randomUUID();
963
- const requestedTitle = body.title;
964
- if (requestedTitle !== void 0 && typeof requestedTitle !== "string") return c.json({ error: "Invalid title" }, 400);
965
- const normalizedTitle = requestedTitle === void 0 ? null : normalizeSessionTitle(requestedTitle);
966
- const requestedBranch = body.branch;
967
- let branch;
968
- if (requestedBranch === void 0) branch = `${USER_SESSION_BRANCH_PREFIX}${sessionId}`;
969
- else if (typeof requestedBranch === "string" && isValidGitRef(requestedBranch)) branch = requestedBranch;
970
- else return c.json({ error: "Invalid branch" }, 400);
971
- if (requestedSessionId !== void 0) {
972
- const existing = await github.sourceControlStorage.sessions.getBySessionId(sessionId);
973
- if (existing) {
974
- if (existing.projectRepositoryId !== project.id || existing.orgId !== orgId || existing.userId !== userId || existing.branch !== branch) return c.json({ error: "Session ID conflict" }, 409);
975
- return c.json({ session: existing });
976
- }
977
- }
978
- const session = await github.sourceControlStorage.sessions.create({
979
- sessionId,
980
- projectRepositoryId: project.id,
981
- factoryProjectId: project.factoryProjectId,
982
- orgId,
983
- userId,
984
- branch,
985
- baseBranch,
986
- title: normalizedTitle,
987
- visibility: "org"
988
- }).catch(async (error) => {
989
- if (!(error instanceof UniqueViolationError) || requestedSessionId === void 0) throw error;
990
- const conflict = await github.sourceControlStorage.sessions.getBySessionId(sessionId);
991
- if (!conflict) throw error;
992
- return conflict;
993
- });
994
- if (requestedSessionId !== void 0 && (session.sessionId !== sessionId || session.projectRepositoryId !== project.id || session.orgId !== orgId || session.userId !== userId || session.branch !== branch)) return c.json({ error: "Session ID conflict" }, 409);
995
- return c.json({ session });
996
- }
997
- }),
998
- registerApiRoute("/web/user-sessions/:sessionId", {
999
- method: "GET",
1000
- requiresAuth: false,
1001
- handler: async (c) => {
1002
- const resolved = await resolveOrgTenant(loose(c), auth);
1003
- if ("response" in resolved) return resolved.response;
1004
- const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
1005
- if (!session || !canViewSourceControlSession(session, resolved.tenant)) return c.json({ error: "Session not found" }, 404);
1006
- const resourceId = await sessionMemoryResourceId(controller, session, workItems);
1007
- if (!canReadSessionResource(session, resourceId, resolved.tenant)) return c.json({ error: "Session not found" }, 404);
1008
- return c.json({ session: {
1009
- ...session,
1010
- resourceId
1011
- } });
1012
- }
1013
- }),
1014
- registerApiRoute("/web/user-sessions/:sessionId", {
1015
- method: "DELETE",
1016
- requiresAuth: false,
1017
- handler: async (c) => {
1018
- const resolved = await resolveOrgTenant(loose(c), auth);
1019
- if ("response" in resolved) return resolved.response;
1020
- const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
1021
- if (!session || session.orgId !== resolved.tenant.orgId || session.userId !== resolved.tenant.userId) return c.json({ error: "Session not found" }, 404);
1022
- try {
1023
- await waitForPendingFilesystemCapture(session.sessionId).catch((error) => {
1024
- console.warn("[GitHub Sessions] Failed to drain filesystem capture before delete", {
1025
- sessionId: session.sessionId,
1026
- error
1027
- });
1028
- });
1029
- await controller?.deleteSession({ sessionId: session.sessionId });
1030
- } catch (error) {
1031
- console.error("[GitHub Sessions] Failed to tear down live controller session", {
1032
- sessionId: session.sessionId,
1033
- error
1034
- });
1035
- }
1036
- if (sessionRetirement) await sessionRetirement.retireSession({
1037
- sourceControl: github.sourceControlStorage,
1038
- ...workItems ? { workItems } : {},
1039
- orgId: session.orgId,
1040
- sessionId: session.sessionId,
1041
- deleteSession: true
1042
- });
1043
- else {
1044
- await workItems?.clearSessionReferences({
1045
- orgId: session.orgId,
1046
- sessionId: session.sessionId
1047
- });
1048
- await github.sourceControlStorage.sessions.delete(session.id);
1049
- reclaimDeletedSessionSandbox({ session }).catch((error) => {
1050
- console.error("[GitHub Sessions] Failed to reclaim sandbox for deleted session", {
1051
- sessionId: session.sessionId,
1052
- sandboxId: session.sandboxId,
1053
- error
1054
- });
1055
- });
1056
- }
1057
- return c.json({ removed: true });
1058
- }
1059
- }),
1060
- registerApiRoute("/web/user-sessions/:sessionId/title", {
1061
- method: "POST",
1062
- requiresAuth: false,
1063
- handler: async (c) => {
1064
- const resolved = await resolveOrgTenant(loose(c), auth);
1065
- if ("response" in resolved) return resolved.response;
1066
- const sessionId = c.req.param("sessionId");
1067
- const row = await github.sourceControlStorage.sessions.getBySessionId(sessionId);
1068
- if (!row || row.orgId !== resolved.tenant.orgId || row.userId !== resolved.tenant.userId) return c.json({ error: "Session not found" }, 404);
1069
- if (!controller) return c.json({ error: "Sessions are not available on this server." }, 503);
1070
- const thread = (await listFactorySessionThreads(controller, row, workItems)).sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())[0];
1071
- if (!thread) return c.json({ error: "This session has no conversation to name yet." }, 409);
1072
- const stored = await memorySettings.get({
1073
- orgId: row.orgId,
1074
- userId: row.userId
1075
- });
1076
- const requestContext = new RequestContext();
1077
- requestContext.set("user", {
1078
- workosId: row.userId,
1079
- organizationId: row.orgId
1080
- });
1081
- requestContext.set("mastra__factoryMemorySettings", stored);
1082
- try {
1083
- const title = await nameSession(sessionId, async () => {
1084
- const generated = await controller.generateThreadTitle({
1085
- threadId: thread.id,
1086
- sessionId,
1087
- requestContext,
1088
- ...stored?.observerModelId ? { model: titleModel(stored.observerModelId) } : {}
1089
- });
1090
- const named = generated ? normalizeSessionTitle(generated) : null;
1091
- if (named) await github.sourceControlStorage.sessions.rename({
1092
- sessionId,
1093
- title: named
1094
- });
1095
- return named;
1096
- });
1097
- if (!title) return c.json({ error: "The model returned an empty title. Try again." }, 502);
1098
- return c.json({ title });
1099
- } catch (error) {
1100
- return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);
1101
- }
1102
- }
1103
- }),
1104
625
  registerApiRoute("/web/github/projects/:id/commit", {
1105
626
  method: "POST",
1106
627
  requiresAuth: false,
@@ -1146,36 +667,6 @@ function buildProjectGitRoutes({ github, auth, sandbox, users, controller, memor
1146
667
  }
1147
668
  }
1148
669
  }),
1149
- registerApiRoute("/web/github/projects/:id/commits", {
1150
- method: "GET",
1151
- requiresAuth: false,
1152
- handler: async (c) => {
1153
- const loaded = await loadOrgProject({
1154
- github,
1155
- auth,
1156
- c: loose(c)
1157
- });
1158
- if ("response" in loaded) return loaded.response;
1159
- const { orgId, project } = loaded;
1160
- const branch = c.req.query("branch") ?? project.defaultBranch;
1161
- if (!isValidGitRef(branch)) return c.json({ error: "Invalid branch" }, 400);
1162
- const limit = Math.min(Math.max(Math.floor(Number(c.req.query("limit") ?? DEFAULT_COMMIT_PAGE)) || DEFAULT_COMMIT_PAGE, 1), MAX_COMMIT_PAGE);
1163
- try {
1164
- const commits = await listRepositoryCommits(github, {
1165
- orgId,
1166
- project,
1167
- branch,
1168
- limit
1169
- });
1170
- return c.json({
1171
- commits,
1172
- branch
1173
- });
1174
- } catch (err) {
1175
- return gitErrorResponse(loose(c), err);
1176
- }
1177
- }
1178
- }),
1179
670
  registerApiRoute("/web/github/projects/:id/push", {
1180
671
  method: "POST",
1181
672
  requiresAuth: false,