@mastra/factory 0.2.3-alpha.0 → 0.3.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/auth.d.ts.map +1 -1
  3. package/dist/auth.js +54 -6
  4. package/dist/auth.js.map +1 -1
  5. package/dist/factory.d.ts +10 -0
  6. package/dist/factory.d.ts.map +1 -1
  7. package/dist/factory.js +35 -4
  8. package/dist/factory.js.map +1 -1
  9. package/dist/index.d.ts +11 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +6 -1
  12. package/dist/integrations/base.d.ts +25 -0
  13. package/dist/integrations/base.d.ts.map +1 -1
  14. package/dist/integrations/github/integration.js +1 -1
  15. package/dist/integrations/github/routes.d.ts.map +1 -1
  16. package/dist/integrations/github/routes.js +23 -8
  17. package/dist/integrations/github/routes.js.map +1 -1
  18. package/dist/integrations/github/sandbox-release.d.ts +38 -0
  19. package/dist/integrations/github/sandbox-release.d.ts.map +1 -0
  20. package/dist/integrations/github/sandbox-release.js +74 -0
  21. package/dist/integrations/github/sandbox-release.js.map +1 -0
  22. package/dist/integrations/github/sandbox.d.ts +10 -0
  23. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  24. package/dist/integrations/github/sandbox.js +18 -1
  25. package/dist/integrations/github/sandbox.js.map +1 -1
  26. package/dist/integrations/platform/github/event-worker.js +1 -1
  27. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  28. package/dist/integrations/platform/github/integration.d.ts +4 -1
  29. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  30. package/dist/integrations/platform/github/integration.js +9 -2
  31. package/dist/integrations/platform/github/integration.js.map +1 -1
  32. package/dist/routes/surface.d.ts +3 -1
  33. package/dist/routes/surface.d.ts.map +1 -1
  34. package/dist/routes/surface.js +2 -1
  35. package/dist/routes/surface.js.map +1 -1
  36. package/dist/rules/dispatcher.d.ts +2 -0
  37. package/dist/rules/dispatcher.d.ts.map +1 -1
  38. package/dist/rules/dispatcher.js +43 -12
  39. package/dist/rules/dispatcher.js.map +1 -1
  40. package/dist/rules/start-coordinator.js +1 -1
  41. package/dist/rules/transition-service.d.ts +17 -0
  42. package/dist/rules/transition-service.d.ts.map +1 -1
  43. package/dist/rules/transition-service.js +29 -1
  44. package/dist/rules/transition-service.js.map +1 -1
  45. package/dist/sandbox/fleet.d.ts +12 -1
  46. package/dist/sandbox/fleet.d.ts.map +1 -1
  47. package/dist/sandbox/fleet.js +35 -1
  48. package/dist/sandbox/fleet.js.map +1 -1
  49. package/dist/spa-static.js +2 -1
  50. package/dist/spa-static.js.map +1 -1
  51. package/dist/state-signing.d.ts +8 -1
  52. package/dist/state-signing.d.ts.map +1 -1
  53. package/dist/state-signing.js +5 -2
  54. package/dist/state-signing.js.map +1 -1
  55. package/dist/storage/domains/channel-identity/base.d.ts +96 -0
  56. package/dist/storage/domains/channel-identity/base.d.ts.map +1 -0
  57. package/dist/storage/domains/channel-identity/base.js +149 -0
  58. package/dist/storage/domains/channel-identity/base.js.map +1 -0
  59. package/dist/storage/domains/source-control/base.d.ts +41 -0
  60. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  61. package/dist/storage/domains/source-control/base.js +59 -0
  62. package/dist/storage/domains/source-control/base.js.map +1 -1
  63. package/dist/storage/domains/source-control/inmemory.d.ts +8 -1
  64. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  65. package/dist/storage/domains/source-control/inmemory.js +18 -0
  66. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  67. package/dist/workspace.d.ts.map +1 -1
  68. package/dist/workspace.js +19 -3
  69. package/dist/workspace.js.map +1 -1
  70. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"integration.js","names":["#client","#endpointHost","#pollingEnabled","#pollingIntervalMs","#reconcileEnabled","#installationReposCache","#repositoryAccessCache","#resolveIntakeDispatch","#listIssues","#listPullRequests","#getIssue","#createIssueComment","#updateIntakeIssue","#storage","#getPullRequest","#createPullRequest","#updatePullRequest","#mergePullRequest","#listComments","#createComment","#updateComment","#deleteComment","#listReviews","#getReview","#createReview","#updateReview","#submitReview","#dismissReview","#deletePendingReview","#listReviewComments","#createReviewComment","#updateReviewComment","#deleteReviewComment","#requestedReviewers","#integrationStorage","#statusRoute","#connectRoute","#connectUserRoute","#syncInstallations","#fetchUserConnection"],"sources":["../../../../src/integrations/platform/github/integration.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport type { IntegrationConnection } from '../../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n UpdateIntakeIssueInput,\n} from '../../../capabilities/intake.js';\nimport type {\n CreatePullRequestCommentInput,\n CreatePullRequestInput,\n CreateReviewCommentInput,\n CreateReviewInput,\n DeletePullRequestCommentInput,\n DismissReviewInput,\n ListPullRequestCommentsInput,\n ListPullRequestsInput,\n ListReviewCommentsInput,\n ListReviewsInput,\n MergePullRequestInput,\n PullRequest,\n PullRequestComment,\n PullRequestRef,\n RepositoryAccess,\n Review,\n ReviewComment,\n ReviewRef,\n SubmitReviewInput,\n UpdatePullRequestCommentInput,\n UpdatePullRequestInput,\n UpdateReviewInput,\n UpdateReviewersInput,\n VersionControl,\n} from '../../../capabilities/version-control.js';\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type {\n SourceControlInstallation,\n SourceControlStorageHandle,\n} from '../../../storage/domains/source-control/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../../base.js';\nimport type { GithubIntegration, GithubRepositoryPermission, RepoSummary } from '../../github/integration.js';\nimport { buildGithubRoutes } from '../../github/routes.js';\nimport { attachGithubReconciler, attachGithubRules } from '../../github/rules.js';\nimport type { ReconcilePullRequestState } from '../../github/rules.js';\nimport {\n createGithubSubscriptionTools,\n parseCreatedPullRequest,\n subscribeCurrentSessionToPullRequest,\n} from '../../github/session-subscriptions.js';\nimport type { GithubSubscriptionStorage } from '../../github/subscriptions.js';\nimport {\n logPlatformInfo,\n logPlatformWarn,\n PlatformApiClient,\n PlatformApiError,\n platformApiClientConfigFromEnv,\n} from '../api-client.js';\nimport { PlatformGithubEventWorker } from './event-worker.js';\nimport type { PlatformGithubEventStorage } from './event-worker.js';\n\ntype GithubActor = { login: string; avatarUrl: string | null; htmlUrl: string | null } | null;\n\ntype PlatformGithubInstallation = {\n installationId: number;\n accountLogin: string;\n accountType: string;\n suspendedAt: string | null;\n usable: boolean;\n};\n\ntype PlatformGithubUserConnection = {\n connected: boolean;\n githubUsername: string | null;\n reason?: 'token-invalid' | 'no-accessible-installation' | 'missing-permissions' | 'verification-unavailable' | null;\n};\n\ntype GithubIssue = {\n number: number;\n state: 'open' | 'closed';\n title: string;\n body: string | null;\n htmlUrl: string;\n labels: string[];\n assignees: string[];\n commentCount: number;\n user: GithubActor;\n createdAt: string;\n updatedAt: string;\n};\n\ntype GithubComment = {\n id: number;\n body: string;\n htmlUrl: string;\n user: GithubActor;\n createdAt: string;\n updatedAt: string;\n};\n\ntype GithubPullRequest = {\n number: number;\n title: string;\n body: string | null;\n state: 'open' | 'closed';\n htmlUrl: string;\n merged: boolean;\n mergeable: boolean | null;\n draft: boolean;\n head: { ref: string; sha: string };\n base: { ref: string; repo: { id: number; fullName: string } };\n user: GithubActor;\n createdAt: string;\n updatedAt: string;\n};\n\ntype GithubReview = {\n id: number;\n htmlUrl: string | null;\n body: string | null;\n state: 'PENDING' | 'COMMENTED' | 'APPROVED' | 'CHANGES_REQUESTED' | 'DISMISSED';\n commitId: string | null;\n submittedAt: string | null;\n user: GithubActor;\n};\n\ntype GithubReviewComment = GithubComment & {\n path: string;\n line: number | null;\n side: 'LEFT' | 'RIGHT' | null;\n commitId: string;\n replyToId: number | null;\n};\n\nconst PAGE_SIZE = 30;\nconst API_PREFIX = '/v1/server';\n/**\n * How long an installation's repository listing may be reused. The repos\n * route and token minting both call it — often several times within one UI\n * interaction — and each call is a full Platform round trip.\n */\nconst INSTALLATION_REPOS_CACHE_TTL_MS = 30_000;\n/**\n * How long a minted repository-scoped token may be reused. GitHub\n * installation tokens live ~60 minutes; 5 minutes keeps a wide validity\n * margin while collapsing the per-session-materialization mint round trip.\n */\nconst REPOSITORY_ACCESS_CACHE_TTL_MS = 5 * 60_000;\n/**\n * Upper bound for both TTL caches. Entries expire lazily on re-access, so\n * without a hard cap keys that stop being queried would accumulate for the\n * integration's (long) lifetime. Insertion-order eviction — matches the\n * bounded verification cache in `@mastra/auth-studio`.\n */\nconst MAX_CACHE_ENTRIES = 1000;\n\nfunction setBounded<K, V>(cache: Map<K, V>, key: K, value: V): void {\n cache.delete(key);\n cache.set(key, value);\n if (cache.size > MAX_CACHE_ENTRIES) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined) cache.delete(oldest);\n }\n}\n\nconst REPOSITORY_TOKEN_PERMISSIONS = {\n contents: 'write',\n issues: 'write',\n pull_requests: 'write',\n} as const;\n\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\nfunction routeBaseUrl(ctx: IntegrationContext, requestUrl: string): string {\n return (ctx.baseUrl || new URL(requestUrl).origin).replace(/\\/+$/, '');\n}\n\nexport class PlatformGithubIntegration implements FactoryIntegration {\n readonly id = 'github';\n readonly #client: PlatformApiClient;\n readonly #endpointHost: string;\n readonly #pollingEnabled: boolean;\n readonly #pollingIntervalMs: number | undefined;\n readonly #reconcileEnabled: boolean;\n #storage: SourceControlStorageHandle | undefined;\n #integrationStorage: GithubSubscriptionStorage | undefined;\n /** installationId → cached repository listing (TTL-bounded). */\n readonly #installationReposCache = new Map<number, { repos: RepoSummary[]; expiresAt: number }>();\n /** `orgId:repositoryId` → cached repository access (TTL-bounded). */\n readonly #repositoryAccessCache = new Map<string, { access: RepositoryAccess; expiresAt: number }>();\n\n readonly intake: Intake = {\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: async ({ orgId, userId }) => {\n const installations = await this.#client.request<{\n installations: Array<{\n installationId: number;\n accountLogin: string;\n accountType: string;\n suspendedAt: string | null;\n usable: boolean;\n }>;\n }>('GET', `${API_PREFIX}/github-app/installations`);\n const usable = installations.installations.filter(\n installation => installation.usable && !installation.suspendedAt,\n );\n const repositories = await Promise.all(\n usable.map(async installation => {\n const storedInstallation = await this.versionControl.registerInstallation({\n orgId,\n userId,\n installation: {\n externalId: String(installation.installationId),\n accountName: installation.accountLogin,\n accountType: installation.accountType,\n },\n });\n const result = await this.#client.request<{\n repositories: Array<{\n id: number;\n fullName: string;\n private: boolean;\n defaultBranch: string;\n htmlUrl: string;\n }>;\n }>('GET', `${API_PREFIX}/github-app/installations/${installation.installationId}/repositories`);\n await this.versionControl.registerRepositories({\n orgId,\n installationId: storedInstallation.id,\n repositories: result.repositories.map(repository => ({\n externalId: String(repository.id),\n slug: repository.fullName,\n defaultBranch: repository.defaultBranch,\n metadata: { private: repository.private, url: repository.htmlUrl },\n })),\n });\n return result.repositories.map(repository => ({ repository, installation }));\n }),\n );\n return repositories.flat().map(({ repository, installation }) => ({\n id: repository.fullName,\n name: repository.fullName,\n type: 'repository',\n metadata: {\n installationId: installation.installationId,\n accountLogin: installation.accountLogin,\n accountType: installation.accountType,\n repositoryId: repository.id,\n defaultBranch: repository.defaultBranch,\n private: repository.private,\n url: repository.htmlUrl,\n },\n }));\n },\n listItems: async ({ sourceIds, cursor }) => {\n const page = parsePositiveCursor(cursor);\n const pages = await Promise.all(\n sourceIds.map(async sourceId => {\n const connection = { type: 'app-installation' as const, installationId: 1 };\n const [issues, pullRequests] = await Promise.all([\n this.#listIssues(connection, sourceId, page),\n this.#listPullRequests({ connection, sourceId, includeDrafts: false, cursor: String(page) }),\n ]);\n return {\n items: [\n ...issues.issues.map(issue => ({\n source: { type: 'issue', externalId: `${sourceId}:${issue.id}`, url: issue.url },\n sourceId,\n title: issue.title,\n status: issue.state ?? undefined,\n labels: issue.labels,\n assignee: issue.assignee,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n metadata: { repository: sourceId, number: Number(issue.id), author: issue.author },\n })),\n ...pullRequests.pullRequests.map(pullRequest => ({\n source: { type: 'pull-request', externalId: `${sourceId}:${pullRequest.id}`, url: pullRequest.url },\n sourceId,\n title: pullRequest.title,\n status: pullRequest.state,\n createdAt: pullRequest.createdAt,\n updatedAt: pullRequest.updatedAt,\n metadata: {\n repository: sourceId,\n number: Number(pullRequest.id),\n author: pullRequest.author,\n baseBranch: pullRequest.baseBranch,\n headBranch: pullRequest.headBranch,\n },\n })),\n ],\n hasNextPage: issues.nextCursor !== null || pullRequests.nextCursor !== null,\n };\n }),\n );\n return {\n items: pages.flatMap(result => result.items),\n nextCursor: pages.some(result => result.hasNextPage) ? String(page + 1) : null,\n };\n },\n listIssues: async input => {\n requireGithubConnection(input.connection);\n const sourceId = requireSingleSource(input.sourceIds, 'GitHub Intake requires exactly one repository source.');\n return this.#listIssues(input.connection, sourceId, parsePositiveCursor(input.cursor), input.labels);\n },\n getIssue: input => this.#getIssue(input.connection, input.sourceId, input.issueId),\n createComment: input => this.#createIssueComment(input),\n updateIssue: input => this.#updateIntakeIssue(input),\n };\n\n readonly versionControl: VersionControl = {\n initialize: ({ storage }) => {\n this.#storage = storage;\n },\n registerInstallation: ({ orgId, userId, installation }) =>\n this.storage.installations.upsert({\n orgId,\n connectedByUserId: userId,\n externalId: installation.externalId,\n accountName: installation.accountName,\n accountType: installation.accountType,\n providerMetadata: installation.metadata,\n }),\n registerRepositories: ({ orgId, installationId, repositories }) =>\n Promise.all(\n repositories.map(repository =>\n this.storage.repositories.upsert({\n orgId,\n input: {\n installationId,\n externalId: repository.externalId,\n slug: repository.slug,\n defaultBranch: repository.defaultBranch,\n providerMetadata: repository.metadata,\n },\n }),\n ),\n ),\n getRepositoryAccess: async ({ orgId, repositoryId }) => {\n // Every session materialization requests access; reuse a recent grant\n // instead of re-minting through the Platform each time. The TTL keeps\n // a wide margin under GitHub's ~60min installation-token lifetime.\n const cacheKey = `${orgId}:${repositoryId}`;\n const cached = this.#repositoryAccessCache.get(cacheKey);\n if (cached && cached.expiresAt > Date.now()) return cached.access;\n this.#repositoryAccessCache.delete(cacheKey);\n\n const repository = await this.storage.repositories.get({ orgId, id: repositoryId });\n if (!repository) throw new Error('Version-control repository not found.');\n const cloneUrl = `https://github.com/${repository.slug}.git`;\n const installation = await this.storage.installations.get({ orgId, id: repository.installationId });\n if (!installation) throw new Error('Version-control installation not found.');\n const installationId = parsePositiveInteger(installation.externalId);\n if (installationId === null) throw new Error('GitHub installation id is invalid.');\n const repositoryName = splitRepository(repository.slug).repo;\n\n try {\n const token = await this.#client.request<{ token: string }>(\n 'POST',\n `${API_PREFIX}/github-app/installations/${installationId}/token`,\n { repositories: [repositoryName], permissions: REPOSITORY_TOKEN_PERMISSIONS },\n );\n const access: RepositoryAccess = {\n cloneUrl,\n authorization: { scheme: 'bearer', token: token.token },\n };\n setBounded(this.#repositoryAccessCache, cacheKey, {\n access,\n expiresAt: Date.now() + REPOSITORY_ACCESS_CACHE_TTL_MS,\n });\n return access;\n } catch (err) {\n // Recover from stale installation: when a GitHub App is uninstalled and reinstalled,\n // GitHub assigns a new installation ID. Platform creates a new installation row,\n // and Factory's intake.listSources creates a new local installation row with the\n // new externalId. Try to find the new installation by accountName.\n if (!isNotFound(err) || !installation.accountName) throw err;\n const installations = await this.storage.installations.list({ orgId });\n const newInstallation = installations.find(\n inst => inst.accountName === installation.accountName && inst.id !== installation.id,\n );\n if (!newInstallation) throw err;\n const newInstallationId = parsePositiveInteger(newInstallation.externalId);\n if (newInstallationId === null) throw err;\n\n // Persist the migration so we don't hit the 404 path on every call.\n // This updates the repository's installation_id to the new installation.\n await this.storage.repositories.migrateInstallation({\n orgId,\n id: repositoryId,\n newInstallationId: newInstallation.id,\n });\n\n const token = await this.#client.request<{ token: string }>(\n 'POST',\n `${API_PREFIX}/github-app/installations/${newInstallationId}/token`,\n { repositories: [repositoryName], permissions: REPOSITORY_TOKEN_PERMISSIONS },\n );\n const access: RepositoryAccess = {\n cloneUrl,\n authorization: { scheme: 'bearer', token: token.token },\n };\n setBounded(this.#repositoryAccessCache, cacheKey, {\n access,\n expiresAt: Date.now() + REPOSITORY_ACCESS_CACHE_TTL_MS,\n });\n return access;\n }\n },\n listPullRequests: input => this.#listPullRequests(input),\n getPullRequest: input => this.#getPullRequest(input),\n createPullRequest: input => this.#createPullRequest(input),\n updatePullRequest: input => this.#updatePullRequest(input),\n closePullRequest: input => this.#updatePullRequest({ ...input, state: 'closed' }),\n mergePullRequest: input => this.#mergePullRequest(input),\n listComments: input => this.#listComments(input),\n createComment: input => this.#createComment(input),\n updateComment: input => this.#updateComment(input),\n deleteComment: input => this.#deleteComment(input),\n listReviews: input => this.#listReviews(input),\n getReview: input => this.#getReview(input),\n createReview: input => this.#createReview(input),\n updateReview: input => this.#updateReview(input),\n submitReview: input => this.#submitReview(input),\n dismissReview: input => this.#dismissReview(input),\n deletePendingReview: input => this.#deletePendingReview(input),\n listReviewComments: input => this.#listReviewComments(input),\n createReviewComment: input => this.#createReviewComment(input),\n updateReviewComment: input => this.#updateReviewComment(input),\n deleteReviewComment: input => this.#deleteReviewComment(input),\n listRequestedReviewers: input => this.#requestedReviewers('GET', input),\n requestReviewers: input => this.#requestedReviewers('POST', input),\n removeRequestedReviewers: input => this.#requestedReviewers('DELETE', input),\n };\n\n constructor() {\n const config = platformApiClientConfigFromEnv();\n this.#client = new PlatformApiClient(config);\n this.#endpointHost = new URL(config.baseUrl).host;\n this.#pollingEnabled = process.env.MASTRA_PLATFORM_GITHUB_POLLING_ENABLED?.trim().toLowerCase() !== 'false';\n this.#pollingIntervalMs = optionalPositiveIntegerEnv('MASTRA_PLATFORM_GITHUB_POLLING_INTERVAL_MS');\n this.#reconcileEnabled = process.env.MASTRA_PLATFORM_GITHUB_RECONCILE_ENABLED?.trim().toLowerCase() !== 'false';\n }\n\n get storage(): SourceControlStorageHandle {\n if (!this.#storage) throw new Error('PlatformGithubIntegration source-control storage has not been initialized.');\n return this.#storage;\n }\n\n get sourceControlStorage(): SourceControlStorageHandle {\n return this.storage;\n }\n\n get integrationStorage(): GithubSubscriptionStorage {\n if (!this.#integrationStorage) {\n throw new Error('PlatformGithubIntegration generic storage has not been initialized.');\n }\n return this.#integrationStorage;\n }\n\n /** Resolve a stored GitHub locator without scanning installations or repositories. */\n async #resolveIntakeDispatch({\n orgId,\n externalSource,\n }: {\n orgId: string;\n externalSource: { type: string; externalId: string };\n }): Promise<{ connection: IntegrationConnection; sourceId: string; issueId: string } | null> {\n const target = parseGithubExternalTarget(externalSource.externalId);\n if (!target) return null;\n const repository = target.repository.includes('/')\n ? target.repository\n : (await this.storage.repositories.findByExternalId({ orgId, externalId: target.repository }))?.slug;\n if (!repository) return null;\n return {\n connection: { type: 'app-installation', installationId: 1 },\n sourceId: repository,\n issueId: target.issueId,\n };\n }\n\n initialize({ storage }: { storage: IntegrationStorageHandle }): void {\n this.#integrationStorage = storage as unknown as GithubSubscriptionStorage;\n logPlatformInfo('Platform GitHub integration initialized', {\n endpointHost: this.#endpointHost,\n pollingEnabled: this.#pollingEnabled,\n pollingIntervalMs: this.#pollingIntervalMs,\n reconcileEnabled: this.#reconcileEnabled,\n });\n }\n\n routes(ctx: IntegrationContext): ApiRoute[] {\n const ingestFactoryEvent = attachGithubRules(this, ctx);\n return [\n this.#statusRoute(ctx),\n this.#connectRoute(ctx),\n this.#connectUserRoute(ctx),\n ...buildGithubRoutes({\n auth: ctx.auth,\n fleet: ctx.fleet,\n storage: ctx.factoryStorage,\n github: this as unknown as GithubIntegration,\n stateSigner: ctx.stateSigner,\n baseUrl: ctx.baseUrl,\n controller: ctx.controller,\n projects: ctx.storage.projects,\n emitAudit: ctx.hooks?.emitAudit,\n ingestFactoryEvent,\n }).filter(\n route =>\n route.path !== '/web/github/status' &&\n route.path !== '/web/github/webhook' &&\n !route.path.startsWith('/auth/github/'),\n ),\n ];\n }\n\n #statusRoute(ctx: IntegrationContext): ApiRoute {\n return registerApiRoute('/web/github/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await ctx.auth.ensureUser(loose(c));\n const tenant = ctx.auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n sandboxEnabled: ctx.fleet.enabled,\n organizationRequired: true,\n connected: false,\n installations: [],\n userConnected: false,\n userGithubUsername: null,\n reason: 'organization_required',\n diagnostics: this.diagnostics(),\n });\n }\n\n const [installations, userConnection] = await Promise.all([\n this.#syncInstallations(tenant.orgId, tenant.userId),\n this.#fetchUserConnection(tenant.userId),\n ]);\n return c.json({\n enabled: true,\n sandboxEnabled: ctx.fleet.enabled,\n connected: installations.length > 0,\n installations: installations.map(installation => ({\n installationId: Number(installation.externalId),\n accountLogin: installation.accountName,\n accountType: installation.accountType,\n })),\n userConnected: userConnection.connected,\n userGithubUsername: userConnection.githubUsername,\n reason: installations.length > 0 ? 'ready' : 'not_connected',\n diagnostics: this.diagnostics(),\n });\n },\n });\n }\n\n #connectRoute(ctx: IntegrationContext): ApiRoute {\n return registerApiRoute('/auth/github/connect', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await ctx.auth.ensureUser(loose(c));\n const tenant = ctx.auth.tenant(loose(c));\n if (!tenant?.orgId) return c.json({ error: 'unauthorized' }, 401);\n\n const redirectTo = c.req.query('redirectTo') || c.req.query('return_to') || '/';\n const originator = routeBaseUrl(ctx, c.req.url);\n logPlatformInfo('Starting Platform GitHub connect flow', {\n orgId: tenant.orgId,\n redirectTo,\n originator,\n });\n const query = new URLSearchParams({\n action: 'install',\n redirectTo,\n originator,\n });\n const { url } = await this.#client.request<{ url: string }>(\n 'GET',\n `${API_PREFIX}/github-app/install-url?${query}`,\n );\n return c.redirect(url);\n },\n });\n }\n\n #connectUserRoute(ctx: IntegrationContext): ApiRoute {\n return registerApiRoute('/auth/github/connect-user', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await ctx.auth.ensureUser(loose(c));\n const tenant = ctx.auth.tenant(loose(c));\n if (!tenant?.orgId) return c.json({ error: 'unauthorized' }, 401);\n\n const redirectTo = c.req.query('redirectTo') || c.req.query('return_to') || '/';\n const originator = routeBaseUrl(ctx, c.req.url);\n logPlatformInfo('Starting Platform GitHub user authorization flow', {\n orgId: tenant.orgId,\n redirectTo,\n originator,\n });\n const query = new URLSearchParams({\n userId: tenant.userId,\n redirectTo,\n originator,\n });\n const { url } = await this.#client.request<{ url: string }>(\n 'GET',\n `${API_PREFIX}/github-app/authenticate?${query}`,\n );\n return c.redirect(url);\n },\n });\n }\n\n /**\n * Personal GitHub connection status for the acting user. Returns\n * not-connected when the platform predates the user-connection endpoint.\n */\n async #fetchUserConnection(userId: string): Promise<PlatformGithubUserConnection> {\n try {\n const connection = await this.#client.request<PlatformGithubUserConnection>(\n 'GET',\n `${API_PREFIX}/github-app/user-connection?${new URLSearchParams({ userId })}`,\n );\n if (!connection.connected && connection.reason) {\n logPlatformWarn('Platform GitHub user connection verification failed', {\n userId,\n reason: connection.reason,\n });\n }\n return connection;\n } catch {\n return { connected: false, githubUsername: null };\n }\n }\n\n async #syncInstallations(orgId: string, userId: string): Promise<SourceControlInstallation[]> {\n const result = await this.#client.request<{ installations: PlatformGithubInstallation[] }>(\n 'GET',\n `${API_PREFIX}/github-app/installations`,\n );\n const usableInstallations = result.installations.filter(\n installation => installation.usable && !installation.suspendedAt,\n );\n return Promise.all(\n usableInstallations.map(installation =>\n this.versionControl.registerInstallation({\n orgId,\n userId,\n installation: {\n externalId: String(installation.installationId),\n accountName: installation.accountLogin,\n accountType: installation.accountType,\n },\n }),\n ),\n );\n }\n\n workers(ctx: IntegrationContext): PlatformGithubEventWorker[] {\n if (!this.#pollingEnabled && !this.#reconcileEnabled) return [];\n if (!ctx.controller) {\n throw new Error('Platform GitHub event polling requires the mounted Mastra Code controller.');\n }\n return [\n new PlatformGithubEventWorker({\n client: this.#client,\n controller: ctx.controller,\n github: this,\n storage: ctx.storage.generic as unknown as PlatformGithubEventStorage,\n ingestFactoryEvent: attachGithubRules(this, ctx),\n reconcileFactoryState: this.#reconcileEnabled\n ? attachGithubReconciler(this, ctx, input => this.fetchPullRequestState(input))\n : undefined,\n pollEventsEnabled: this.#pollingEnabled,\n intervalMs: this.#pollingIntervalMs,\n }),\n ];\n }\n\n /**\n * Reads live PR state through the Platform GitHub proxy for the merge\n * reconciler. Returns undefined when the PR cannot be resolved (missing,\n * proxy error) so a sweep never fabricates a merge.\n */\n async fetchPullRequestState(input: {\n installationId: number;\n repository: string;\n number: number;\n }): Promise<ReconcilePullRequestState | undefined> {\n let repository: { owner: string; repo: string };\n try {\n repository = splitRepository(input.repository);\n } catch {\n return undefined;\n }\n try {\n const result = await this.#client.request<{\n title?: string;\n html_url?: string;\n state?: string;\n merged?: boolean;\n created_at?: string;\n merged_by?: { login?: string } | null;\n head?: { ref?: string };\n base?: { ref?: string };\n }>(\n 'GET',\n `${API_PREFIX}/github/repos/${encodeURIComponent(repository.owner)}/${encodeURIComponent(repository.repo)}/pulls/${input.number}`,\n );\n return {\n title: result.title ?? `PR ${input.number}`,\n url: result.html_url ?? `https://github.com/${input.repository}/pull/${input.number}`,\n state: result.state === 'closed' ? 'closed' : 'open',\n merged: result.merged === true,\n headBranch: result.head?.ref ?? '',\n baseBranch: result.base?.ref ?? '',\n ...(result.created_at ? { createdAt: result.created_at } : {}),\n ...(result.merged_by?.login ? { mergedBy: result.merged_by.login } : {}),\n };\n } catch {\n return undefined;\n }\n }\n\n sessionTools({ requestContext }: { requestContext: RequestContext }): IntegrationTools {\n return createGithubSubscriptionTools(requestContext, this as unknown as GithubIntegration);\n }\n\n async postToolObserver({\n toolContext,\n requestContext,\n }: Parameters<NonNullable<FactoryIntegration['postToolObserver']>>[0]): Promise<void> {\n const pullRequestUrl = parseCreatedPullRequest(toolContext);\n if (!pullRequestUrl || !requestContext) return;\n await subscribeCurrentSessionToPullRequest(\n requestContext,\n pullRequestUrl,\n 'auto-gh-pr-create',\n this as unknown as GithubIntegration,\n );\n }\n\n diagnostics(): Record<string, unknown> {\n return {\n mode: 'platform',\n endpointHost: this.#endpointHost,\n polling: {\n enabled: this.#pollingEnabled,\n ...(this.#pollingIntervalMs === undefined ? {} : { intervalMs: this.#pollingIntervalMs }),\n },\n reconcile: { enabled: this.#reconcileEnabled },\n };\n }\n\n async getRepositoryCollaboratorPermission(\n _installationId: number,\n repoFullName: string,\n username: string,\n signal?: AbortSignal,\n ): Promise<GithubRepositoryPermission | undefined> {\n let repository: { owner: string; repo: string };\n try {\n repository = splitRepository(repoFullName);\n } catch {\n return undefined;\n }\n try {\n const result = await this.#client.request<{ permission: GithubRepositoryPermission }>(\n 'GET',\n `${API_PREFIX}/github/repos/${encodeURIComponent(repository.owner)}/${encodeURIComponent(repository.repo)}/collaborators/${encodeURIComponent(username)}/permission`,\n undefined,\n { signal },\n );\n return result.permission;\n } catch {\n return undefined;\n }\n }\n\n async listInstallationRepos(installationId: number): Promise<RepoSummary[]> {\n // Hot in two places — the repos route and token minting (which re-lists\n // only to validate the 1–10 repo rule). A short TTL collapses repeat\n // Platform round trips within one UI interaction.\n const cached = this.#installationReposCache.get(installationId);\n if (cached && cached.expiresAt > Date.now()) return cached.repos;\n this.#installationReposCache.delete(installationId);\n\n const result = await this.#client.request<{\n repositories: Array<{\n id: number;\n owner: string;\n name: string;\n fullName: string;\n private: boolean;\n defaultBranch: string;\n }>;\n }>('GET', `${API_PREFIX}/github-app/installations/${installationId}/repositories`);\n const repos = result.repositories.map(repository => ({ ...repository, installationId }));\n setBounded(this.#installationReposCache, installationId, {\n repos,\n expiresAt: Date.now() + INSTALLATION_REPOS_CACHE_TTL_MS,\n });\n return repos;\n }\n\n async mintInstallationToken(installationId: number): Promise<string> {\n const repositories = await this.listInstallationRepos(installationId);\n if (repositories.length === 0 || repositories.length > 10) {\n throw new Error('Platform GitHub token minting requires between one and ten installation repositories.');\n }\n const result = await this.#client.request<{ token: string }>(\n 'POST',\n `${API_PREFIX}/github-app/installations/${installationId}/token`,\n { repositories: repositories.map(repository => repository.name), permissions: REPOSITORY_TOKEN_PERMISSIONS },\n );\n return result.token;\n }\n\n async addIssueLabels(\n _installationId: number,\n sourceId: string,\n issueNumber: number,\n labels: string[],\n ): Promise<string[]> {\n const result = await this.#client.request<{ labels: string[] }>(\n 'POST',\n repositoryPath(sourceId, `issues/${issueNumber}/labels`),\n { labels },\n );\n return result.labels;\n }\n\n getInstallationOctokit(_installationId: number): ReturnType<GithubIntegration['getInstallationOctokit']> {\n return {\n pulls: {\n get: async ({ owner, repo, pull_number }: { owner: string; repo: string; pull_number: number }) => {\n const data = await this.#client.request<GithubPullRequest>(\n 'GET',\n repositoryPath(`${owner}/${repo}`, `pulls/${pull_number}`),\n );\n return { data: { base: { repo: { id: data.base.repo.id } } } };\n },\n },\n } as unknown as ReturnType<GithubIntegration['getInstallationOctokit']>;\n }\n\n async #listIssues(connection: IntegrationConnection, sourceId: string, page: number, labels?: string[]) {\n requireGithubConnection(connection);\n const path = repositoryPath(sourceId, 'issues');\n const query = new URLSearchParams({ state: 'open', page: String(page), per_page: String(PAGE_SIZE) });\n const normalizedLabels = normalizeLabels(labels);\n if (normalizedLabels.length > 0) query.set('label', normalizedLabels.join(','));\n const result = await this.#client.request<{ issues: GithubIssue[] }>('GET', `${path}?${query}`);\n return {\n issues: result.issues.map(issue => parseIntakeIssue(sourceId, issue)),\n nextCursor: result.issues.length === PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #getIssue(connection: IntegrationConnection, sourceId: string | undefined, issueId: string) {\n requireGithubConnection(connection);\n const repository = requireSource(sourceId, 'GitHub Intake requires a repository source.');\n const issueNumber = requirePositiveId(issueId, 'issue');\n try {\n const [issue, comments] = await Promise.all([\n this.#client.request<GithubIssue>('GET', repositoryPath(repository, `issues/${issueNumber}`)),\n this.#client.request<{ comments: GithubComment[] }>(\n 'GET',\n `${repositoryPath(repository, `issues/${issueNumber}/comments`)}?per_page=100`,\n ),\n ]);\n return parseIntakeIssueDetail(repository, issue, comments.comments);\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n async #updateIntakeIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> {\n requireGithubConnection(input.connection);\n const repository = requireSource(input.sourceId, 'GitHub Intake requires a repository source.');\n const issueNumber = requirePositiveId(input.issueId, 'issue');\n if (input.state.kind === 'byName') {\n logPlatformWarn(`Platform GitHub: updateIssue byName is not supported (name=${input.state.name}); ignoring.`);\n return null;\n }\n const targetState: 'open' | 'closed' =\n input.state.stateType === 'unstarted' || input.state.stateType === 'started' ? 'open' : 'closed';\n const stateReason: 'completed' | 'not_planned' | null =\n targetState === 'closed' ? (input.state.stateType === 'canceled' ? 'not_planned' : 'completed') : null;\n // Reject PR targets: probe the pulls endpoint. A 200 means the number is a\n // pull request, not an issue. Factory does not close PRs via updateIssue —\n // PR merges/closes go through the version-control pipeline.\n try {\n await this.#client.request<GithubPullRequest>('GET', repositoryPath(repository, `pulls/${issueNumber}`));\n logPlatformWarn(`Platform GitHub: updateIssue rejected — target ${repository}#${issueNumber} is a pull request.`);\n return null;\n } catch (error) {\n if (!isNotFound(error)) throw error;\n // 404 on pulls means it's an issue (or nothing) — fall through to PATCH.\n }\n try {\n const issue = await this.#client.request<GithubIssue>(\n 'PATCH',\n repositoryPath(repository, `issues/${issueNumber}`),\n {\n state: targetState,\n ...(stateReason ? { state_reason: stateReason } : {}),\n },\n { actingUserId: input.actingUserId },\n );\n return parseIntakeIssue(repository, issue);\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n async #createIssueComment(input: CreateIntakeCommentInput) {\n requireGithubConnection(input.connection);\n const repository = requireSource(input.sourceId, 'GitHub Intake requires a repository source.');\n const issueNumber = requirePositiveId(input.issueId, 'issue');\n try {\n const comment = await this.#client.request<GithubComment>(\n 'POST',\n repositoryPath(repository, `issues/${issueNumber}/comments`),\n { body: input.body },\n { actingUserId: input.actingUserId },\n );\n return { id: String(comment.id), url: comment.htmlUrl };\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n async #listPullRequests(input: ListPullRequestsInput) {\n requireGithubConnection(input.connection);\n const page = parsePositiveCursor(input.cursor);\n const query = new URLSearchParams({\n state: input.state ?? 'open',\n page: String(page),\n per_page: String(PAGE_SIZE),\n });\n const result = await this.#client.request<{ pullRequests: GithubPullRequest[] }>(\n 'GET',\n `${repositoryPath(input.sourceId, 'pulls')}?${query}`,\n );\n return {\n pullRequests: result.pullRequests\n .filter(pullRequest => input.includeDrafts !== false || !pullRequest.draft)\n .map(parsePullRequest),\n nextCursor: result.pullRequests.length === PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #getPullRequest(input: PullRequestRef) {\n try {\n return parsePullRequest(\n await this.#client.request<GithubPullRequest>('GET', pullRequestPath(input, input.pullRequestId)),\n );\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n async #createPullRequest(input: CreatePullRequestInput) {\n requireGithubConnection(input.connection);\n const result = await this.#client.request<GithubPullRequest>(\n 'POST',\n repositoryPath(input.sourceId, 'pulls'),\n {\n head: input.headBranch,\n base: input.baseBranch,\n title: input.title,\n body: input.body,\n draft: input.draft,\n },\n { actingUserId: input.actingUserId },\n );\n return parsePullRequest(result);\n }\n\n async #updatePullRequest(input: UpdatePullRequestInput) {\n const result = await this.#client.request<GithubPullRequest>(\n 'PATCH',\n pullRequestPath(input, input.pullRequestId),\n {\n title: input.title,\n body: input.body === null ? '' : input.body,\n base: input.baseBranch,\n state: input.state,\n },\n { actingUserId: input.actingUserId },\n );\n return parsePullRequest(result);\n }\n\n #mergePullRequest(input: MergePullRequestInput) {\n return this.#client.request<{ merged: boolean; message: string; sha: string | null }>(\n 'PUT',\n `${pullRequestPath(input, input.pullRequestId)}/merge`,\n { commitTitle: input.commitTitle, commitMessage: input.commitMessage, method: input.method },\n { actingUserId: input.actingUserId },\n );\n }\n\n async #listComments(input: ListPullRequestCommentsInput) {\n const page = parsePositiveCursor(input.cursor);\n const result = await this.#client.request<{ comments: GithubComment[] }>(\n 'GET',\n `${repositoryPath(input.sourceId, `issues/${requirePositiveId(input.pullRequestId, 'pull request')}/comments`)}?page=${page}&per_page=${PAGE_SIZE}`,\n );\n return {\n comments: result.comments.map(parseComment),\n nextCursor: result.comments.length === PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #createComment(input: CreatePullRequestCommentInput) {\n const comment = await this.#client.request<GithubComment>(\n 'POST',\n repositoryPath(input.sourceId, `issues/${requirePositiveId(input.pullRequestId, 'pull request')}/comments`),\n { body: input.body },\n { actingUserId: input.actingUserId },\n );\n return parseComment(comment);\n }\n\n async #updateComment(input: UpdatePullRequestCommentInput) {\n requireGithubConnection(input.connection);\n const comment = await this.#client.request<GithubComment>(\n 'PATCH',\n repositoryPath(input.sourceId, `issues/comments/${requirePositiveId(input.commentId, 'comment')}`),\n { body: input.body },\n { actingUserId: input.actingUserId },\n );\n return parseComment(comment);\n }\n\n async #deleteComment(input: DeletePullRequestCommentInput) {\n requireGithubConnection(input.connection);\n await this.#client.request<void>(\n 'DELETE',\n repositoryPath(input.sourceId, `issues/comments/${requirePositiveId(input.commentId, 'comment')}`),\n undefined,\n { actingUserId: input.actingUserId },\n );\n }\n\n async #listReviews(input: ListReviewsInput) {\n const page = parsePositiveCursor(input.cursor);\n const result = await this.#client.request<{ reviews: GithubReview[] }>(\n 'GET',\n `${pullRequestPath(input, input.pullRequestId)}/reviews?page=${page}&per_page=${PAGE_SIZE}`,\n );\n return {\n reviews: result.reviews.map(parseReview),\n nextCursor: result.reviews.length === PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #getReview(input: ReviewRef) {\n try {\n return parseReview(\n await this.#client.request<GithubReview>(\n 'GET',\n `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, 'review')}`,\n ),\n );\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n async #createReview(input: CreateReviewInput) {\n const review = await this.#client.request<GithubReview>(\n 'POST',\n `${pullRequestPath(input, input.pullRequestId)}/reviews`,\n { body: input.body, commitId: input.commitId, event: input.event ? reviewEvent(input.event) : undefined },\n { actingUserId: input.actingUserId },\n );\n return parseReview(review);\n }\n\n async #updateReview(input: UpdateReviewInput) {\n const review = await this.#client.request<GithubReview>(\n 'PUT',\n `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, 'review')}`,\n { body: input.body },\n { actingUserId: input.actingUserId },\n );\n return parseReview(review);\n }\n\n async #submitReview(input: SubmitReviewInput) {\n const review = await this.#client.request<GithubReview>(\n 'POST',\n `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, 'review')}/events`,\n { body: input.body, event: reviewEvent(input.event) },\n { actingUserId: input.actingUserId },\n );\n return parseReview(review);\n }\n\n async #dismissReview(input: DismissReviewInput) {\n const review = await this.#client.request<GithubReview>(\n 'PUT',\n `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, 'review')}/dismissals`,\n { message: input.message },\n { actingUserId: input.actingUserId },\n );\n return parseReview(review);\n }\n\n async #deletePendingReview(input: ReviewRef) {\n await this.#client.request<void>(\n 'DELETE',\n `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, 'review')}`,\n undefined,\n { actingUserId: input.actingUserId },\n );\n }\n\n async #listReviewComments(input: ListReviewCommentsInput) {\n const page = parsePositiveCursor(input.cursor);\n const result = await this.#client.request<{ comments: GithubReviewComment[] }>(\n 'GET',\n `${pullRequestPath(input, input.pullRequestId)}/comments?page=${page}&per_page=${PAGE_SIZE}`,\n );\n return {\n comments: result.comments.map(parseReviewComment),\n nextCursor: result.comments.length === PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #createReviewComment(input: CreateReviewCommentInput) {\n let body: Record<string, unknown>;\n if (input.replyToId !== undefined) {\n body = { body: input.body, replyToId: requirePositiveId(input.replyToId, 'review comment') };\n } else {\n if (!input.commitId || !input.path || input.line === undefined || !input.side) {\n throw new Error('A review comment requires commitId, path, line, and side unless it is a reply.');\n }\n body = {\n body: input.body,\n commitId: input.commitId,\n path: input.path,\n line: input.line,\n side: input.side.toUpperCase(),\n startLine: input.startLine,\n startSide: input.startSide?.toUpperCase(),\n };\n }\n return parseReviewComment(\n await this.#client.request<GithubReviewComment>(\n 'POST',\n `${pullRequestPath(input, input.pullRequestId)}/comments`,\n body,\n { actingUserId: input.actingUserId },\n ),\n );\n }\n\n async #updateReviewComment(input: UpdatePullRequestCommentInput) {\n requireGithubConnection(input.connection);\n return parseReviewComment(\n await this.#client.request<GithubReviewComment>(\n 'PATCH',\n repositoryPath(input.sourceId, `pulls/comments/${requirePositiveId(input.commentId, 'review comment')}`),\n { body: input.body },\n { actingUserId: input.actingUserId },\n ),\n );\n }\n\n async #deleteReviewComment(input: DeletePullRequestCommentInput) {\n requireGithubConnection(input.connection);\n await this.#client.request<void>(\n 'DELETE',\n repositoryPath(input.sourceId, `pulls/comments/${requirePositiveId(input.commentId, 'review comment')}`),\n undefined,\n { actingUserId: input.actingUserId },\n );\n }\n\n #requestedReviewers(method: 'GET' | 'POST' | 'DELETE', input: UpdateReviewersInput) {\n requireGithubConnection(input.connection);\n return this.#client.request<{ users: string[]; teams: string[] }>(\n method,\n `${pullRequestPath(input, input.pullRequestId)}/requested-reviewers`,\n method === 'GET' ? undefined : { users: input.users, teams: input.teams },\n method === 'GET' ? undefined : { actingUserId: input.actingUserId },\n );\n }\n}\n\nfunction repositoryPath(sourceId: string, suffix: string): string {\n const { owner, repo } = splitRepository(sourceId);\n return `${API_PREFIX}/github/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${suffix}`;\n}\n\nfunction pullRequestPath(\n input: { connection: IntegrationConnection; sourceId: string },\n pullRequestId: string,\n): string {\n requireGithubConnection(input.connection);\n return repositoryPath(input.sourceId, `pulls/${requirePositiveId(pullRequestId, 'pull request')}`);\n}\n\nfunction splitRepository(sourceId: string): { owner: string; repo: string } {\n const slash = sourceId.indexOf('/');\n if (slash <= 0 || slash === sourceId.length - 1) {\n throw new Error('GitHub capabilities require an owner/repository source.');\n }\n return { owner: sourceId.slice(0, slash), repo: sourceId.slice(slash + 1) };\n}\n\nfunction parseIntakeIssue(sourceId: string, issue: GithubIssue): IntakeIssue {\n return {\n id: String(issue.number),\n identifier: `#${issue.number}`,\n title: issue.title,\n url: issue.htmlUrl,\n author: issue.user?.login ?? null,\n state: issue.state,\n stateType: issue.state,\n priority: null,\n assignee: issue.assignees[0] ?? null,\n source: sourceId,\n labels: issue.labels,\n commentCount: issue.commentCount,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\nfunction parseIntakeIssueDetail(sourceId: string, issue: GithubIssue, comments: GithubComment[]): IntakeIssueDetail {\n return {\n ...parseIntakeIssue(sourceId, issue),\n description: issue.body?.trim() ? issue.body : null,\n comments: comments.map(comment => ({\n author: comment.user?.login ?? null,\n body: comment.body,\n createdAt: comment.createdAt,\n })),\n };\n}\n\nfunction parsePullRequest(pullRequest: GithubPullRequest): PullRequest {\n return {\n id: String(pullRequest.number),\n title: pullRequest.title,\n url: pullRequest.htmlUrl,\n author: pullRequest.user?.login ?? null,\n body: pullRequest.body?.trim() ? pullRequest.body : null,\n state: pullRequest.state,\n draft: pullRequest.draft,\n merged: pullRequest.merged,\n mergeable: pullRequest.mergeable,\n baseBranch: pullRequest.base.ref,\n headBranch: pullRequest.head.ref,\n headSha: pullRequest.head.sha,\n createdAt: pullRequest.createdAt,\n updatedAt: pullRequest.updatedAt,\n };\n}\n\nfunction parseComment(comment: GithubComment): PullRequestComment {\n return {\n id: String(comment.id),\n url: comment.htmlUrl,\n author: comment.user?.login ?? null,\n body: comment.body,\n createdAt: comment.createdAt,\n updatedAt: comment.updatedAt,\n };\n}\n\nfunction parseReview(review: GithubReview): Review {\n const states: Record<GithubReview['state'], Review['state']> = {\n PENDING: 'pending',\n COMMENTED: 'commented',\n APPROVED: 'approved',\n CHANGES_REQUESTED: 'changes-requested',\n DISMISSED: 'dismissed',\n };\n return {\n id: String(review.id),\n url: review.htmlUrl,\n author: review.user?.login ?? null,\n body: review.body?.trim() ? review.body : null,\n state: states[review.state],\n commitId: review.commitId,\n submittedAt: review.submittedAt,\n };\n}\n\nfunction parseReviewComment(comment: GithubReviewComment): ReviewComment {\n return {\n ...parseComment(comment),\n path: comment.path,\n line: comment.line,\n side: comment.side?.toLowerCase() as 'left' | 'right' | null,\n commitId: comment.commitId,\n replyToId: comment.replyToId === null ? null : String(comment.replyToId),\n };\n}\n\nfunction requireGithubConnection(connection: IntegrationConnection): void {\n if (connection.type !== 'app-installation' && connection.type !== 'oauth') {\n throw new Error('GitHub capabilities require a GitHub connection.');\n }\n}\n\nfunction requireSingleSource(sourceIds: string[], message: string): string {\n if (sourceIds.length !== 1) throw new Error(message);\n return sourceIds[0]!;\n}\n\nfunction requireSource(sourceId: string | undefined, message: string): string {\n if (!sourceId) throw new Error(message);\n return sourceId;\n}\n\nfunction normalizeLabels(labels: string[] | undefined): string[] {\n return [...new Set((labels ?? []).map(label => label.trim()).filter(Boolean))];\n}\n\nfunction parsePositiveCursor(cursor: string | undefined): number {\n if (cursor === undefined) return 1;\n const parsed = parsePositiveInteger(cursor);\n if (parsed === null) throw new Error('GitHub cursor must be a positive page number.');\n return parsed;\n}\n\nfunction parsePositiveInteger(value: string): number | null {\n if (!/^\\d+$/.test(value)) return null;\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;\n}\n\nfunction parseGithubExternalTarget(externalId: string): { repository: string; issueId: string } | null {\n const match =\n externalId.match(/^(.+\\/.+):(\\d+)$/) ??\n externalId.match(/^github:(\\d+):(?:issue|pull-request):(\\d+)$/) ??\n externalId.match(/^(\\d+):(\\d+)$/);\n if (!match?.[1] || !match[2] || parsePositiveInteger(match[2]) === null) return null;\n return { repository: match[1], issueId: match[2] };\n}\n\nfunction optionalPositiveIntegerEnv(name: 'MASTRA_PLATFORM_GITHUB_POLLING_INTERVAL_MS'): number | undefined {\n const value = process.env[name]?.trim();\n if (!value) return undefined;\n const parsed = parsePositiveInteger(value);\n if (parsed === null) throw new Error(`${name} must be a positive integer.`);\n return parsed;\n}\n\nfunction requirePositiveId(value: string, resource: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed === null) throw new Error(`GitHub ${resource} id must be a positive integer.`);\n return parsed;\n}\n\nfunction reviewEvent(event: 'approve' | 'request-changes' | 'comment') {\n if (event === 'approve') return 'APPROVE' as const;\n if (event === 'request-changes') return 'REQUEST_CHANGES' as const;\n return 'COMMENT' as const;\n}\n\nfunction isNotFound(error: unknown): boolean {\n return error instanceof PlatformApiError && error.status === 404;\n}\n"],"mappings":";;;;;;;AA0IA,MAAM,YAAY;AAClB,MAAM,aAAa;;;;;;AAMnB,MAAM,kCAAkC;;;;;;AAMxC,MAAM,iCAAiC,IAAI;;;;;;;AAO3C,MAAM,oBAAoB;AAE1B,SAAS,WAAiB,OAAkB,KAAQ,OAAgB;CAClE,MAAM,OAAO,GAAG;CAChB,MAAM,IAAI,KAAK,KAAK;CACpB,IAAI,MAAM,OAAO,mBAAmB;EAClC,MAAM,SAAS,MAAM,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;EACnC,IAAI,WAAW,KAAA,GAAW,MAAM,OAAO,MAAM;CAC/C;AACF;AAEA,MAAM,+BAA+B;CACnC,UAAU;CACV,QAAQ;CACR,eAAe;AACjB;AAEA,SAAS,MAAM,GAAqB;CAClC,OAAO;AACT;AAEA,SAAS,aAAa,KAAyB,YAA4B;CACzE,QAAQ,IAAI,WAAW,IAAI,IAAI,UAAU,CAAC,CAAC,OAAA,CAAQ,QAAQ,QAAQ,EAAE;AACvE;AAEA,IAAa,4BAAb,MAAqE;CACnE,KAAc;CACd;CACA;CACA;CACA;CACA;CACA;CACA;;CAEA,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AAoC;CAC/D,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,SAAS,qBAAqB,MAAM;CAC1C,IAAI,WAAW,MAAM,MAAM,IAAI,MAAM,+CAA+C;CACpF,OAAO;AACT;AAEA,SAAS,qBAAqB,OAA8B;CAC1D,IAAI,CAAC,QAAQ,KAAK,KAAK,GAAG,OAAO;CACjC,MAAM,SAAS,OAAO,KAAK;CAC3B,OAAO,OAAO,cAAc,MAAM,KAAK,SAAS,IAAI,SAAS;AAC/D;AAEA,SAAS,0BAA0B,YAAoE;CACrG,MAAM,QACJ,WAAW,MAAM,kBAAkB,KACnC,WAAW,MAAM,6CAA6C,KAC9D,WAAW,MAAM,eAAe;CAClC,IAAI,CAAC,QAAQ,MAAM,CAAC,MAAM,MAAM,qBAAqB,MAAM,EAAE,MAAM,MAAM,OAAO;CAChF,OAAO;EAAE,YAAY,MAAM;EAAI,SAAS,MAAM;CAAG;AACnD;AAEA,SAAS,2BAA2B,MAAwE;CAC1G,MAAM,QAAQ,QAAQ,IAAI,KAAK,EAAE,KAAK;CACtC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,SAAS,qBAAqB,KAAK;CACzC,IAAI,WAAW,MAAM,MAAM,IAAI,MAAM,GAAG,KAAK,6BAA6B;CAC1E,OAAO;AACT;AAEA,SAAS,kBAAkB,OAAe,UAA0B;CAClE,MAAM,SAAS,qBAAqB,KAAK;CACzC,IAAI,WAAW,MAAM,MAAM,IAAI,MAAM,UAAU,SAAS,gCAAgC;CACxF,OAAO;AACT;AAEA,SAAS,YAAY,OAAkD;CACrE,IAAI,UAAU,WAAW,OAAO;CAChC,IAAI,UAAU,mBAAmB,OAAO;CACxC,OAAO;AACT;AAEA,SAAS,WAAW,OAAyB;CAC3C,OAAO,iBAAiB,oBAAoB,MAAM,WAAW;AAC/D"}
1
+ {"version":3,"file":"integration.js","names":["#client","#endpointHost","#pollingEnabled","#pollingIntervalMs","#reconcileEnabled","#installationReposCache","#repositoryAccessCache","#runIssueTriage","#resolveIntakeDispatch","#listIssues","#listPullRequests","#getIssue","#createIssueComment","#updateIntakeIssue","#storage","#getPullRequest","#createPullRequest","#updatePullRequest","#mergePullRequest","#listComments","#createComment","#updateComment","#deleteComment","#listReviews","#getReview","#createReview","#updateReview","#submitReview","#dismissReview","#deletePendingReview","#listReviewComments","#createReviewComment","#updateReviewComment","#deleteReviewComment","#requestedReviewers","#integrationStorage","#statusRoute","#connectRoute","#connectUserRoute","#syncInstallations","#fetchUserConnection"],"sources":["../../../../src/integrations/platform/github/integration.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport type { IntegrationConnection } from '../../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n UpdateIntakeIssueInput,\n} from '../../../capabilities/intake.js';\nimport type {\n CreatePullRequestCommentInput,\n CreatePullRequestInput,\n CreateReviewCommentInput,\n CreateReviewInput,\n DeletePullRequestCommentInput,\n DismissReviewInput,\n ListPullRequestCommentsInput,\n ListPullRequestsInput,\n ListReviewCommentsInput,\n ListReviewsInput,\n MergePullRequestInput,\n PullRequest,\n PullRequestComment,\n PullRequestRef,\n RepositoryAccess,\n Review,\n ReviewComment,\n ReviewRef,\n SubmitReviewInput,\n UpdatePullRequestCommentInput,\n UpdatePullRequestInput,\n UpdateReviewInput,\n UpdateReviewersInput,\n VersionControl,\n} from '../../../capabilities/version-control.js';\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type {\n SourceControlInstallation,\n SourceControlStorageHandle,\n} from '../../../storage/domains/source-control/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../../base.js';\nimport type { GithubIntegration, GithubRepositoryPermission, RepoSummary } from '../../github/integration.js';\nimport type { GithubIssueTriageInput, GithubIssueTriageResult } from '../../github/issue-triage.js';\nimport { runGithubIssueTriage } from '../../github/issue-triage.js';\nimport { buildGithubRoutes } from '../../github/routes.js';\nimport { attachGithubReconciler, attachGithubRules } from '../../github/rules.js';\nimport type { ReconcilePullRequestState } from '../../github/rules.js';\nimport {\n createGithubSubscriptionTools,\n parseCreatedPullRequest,\n subscribeCurrentSessionToPullRequest,\n} from '../../github/session-subscriptions.js';\nimport type { GithubSubscriptionStorage } from '../../github/subscriptions.js';\nimport {\n logPlatformInfo,\n logPlatformWarn,\n PlatformApiClient,\n PlatformApiError,\n platformApiClientConfigFromEnv,\n} from '../api-client.js';\nimport { PlatformGithubEventWorker } from './event-worker.js';\nimport type { PlatformGithubEventStorage } from './event-worker.js';\n\ntype GithubActor = { login: string; avatarUrl: string | null; htmlUrl: string | null } | null;\n\ntype PlatformGithubInstallation = {\n installationId: number;\n accountLogin: string;\n accountType: string;\n suspendedAt: string | null;\n usable: boolean;\n};\n\ntype PlatformGithubUserConnection = {\n connected: boolean;\n githubUsername: string | null;\n reason?: 'token-invalid' | 'no-accessible-installation' | 'missing-permissions' | 'verification-unavailable' | null;\n};\n\ntype GithubIssue = {\n number: number;\n state: 'open' | 'closed';\n title: string;\n body: string | null;\n htmlUrl: string;\n labels: string[];\n assignees: string[];\n commentCount: number;\n user: GithubActor;\n createdAt: string;\n updatedAt: string;\n};\n\ntype GithubComment = {\n id: number;\n body: string;\n htmlUrl: string;\n user: GithubActor;\n createdAt: string;\n updatedAt: string;\n};\n\ntype GithubPullRequest = {\n number: number;\n title: string;\n body: string | null;\n state: 'open' | 'closed';\n htmlUrl: string;\n merged: boolean;\n mergeable: boolean | null;\n draft: boolean;\n head: { ref: string; sha: string };\n base: { ref: string; repo: { id: number; fullName: string } };\n user: GithubActor;\n createdAt: string;\n updatedAt: string;\n};\n\ntype GithubReview = {\n id: number;\n htmlUrl: string | null;\n body: string | null;\n state: 'PENDING' | 'COMMENTED' | 'APPROVED' | 'CHANGES_REQUESTED' | 'DISMISSED';\n commitId: string | null;\n submittedAt: string | null;\n user: GithubActor;\n};\n\ntype GithubReviewComment = GithubComment & {\n path: string;\n line: number | null;\n side: 'LEFT' | 'RIGHT' | null;\n commitId: string;\n replyToId: number | null;\n};\n\nconst PAGE_SIZE = 30;\nconst API_PREFIX = '/v1/server';\n/**\n * How long an installation's repository listing may be reused. The repos\n * route and token minting both call it — often several times within one UI\n * interaction — and each call is a full Platform round trip.\n */\nconst INSTALLATION_REPOS_CACHE_TTL_MS = 30_000;\n/**\n * How long a minted repository-scoped token may be reused. GitHub\n * installation tokens live ~60 minutes; 5 minutes keeps a wide validity\n * margin while collapsing the per-session-materialization mint round trip.\n */\nconst REPOSITORY_ACCESS_CACHE_TTL_MS = 5 * 60_000;\n/**\n * Upper bound for both TTL caches. Entries expire lazily on re-access, so\n * without a hard cap keys that stop being queried would accumulate for the\n * integration's (long) lifetime. Insertion-order eviction — matches the\n * bounded verification cache in `@mastra/auth-studio`.\n */\nconst MAX_CACHE_ENTRIES = 1000;\n\nfunction setBounded<K, V>(cache: Map<K, V>, key: K, value: V): void {\n cache.delete(key);\n cache.set(key, value);\n if (cache.size > MAX_CACHE_ENTRIES) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined) cache.delete(oldest);\n }\n}\n\nconst REPOSITORY_TOKEN_PERMISSIONS = {\n contents: 'write',\n issues: 'write',\n pull_requests: 'write',\n} as const;\n\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\nfunction routeBaseUrl(ctx: IntegrationContext, requestUrl: string): string {\n return (ctx.baseUrl || new URL(requestUrl).origin).replace(/\\/+$/, '');\n}\n\nexport class PlatformGithubIntegration implements FactoryIntegration {\n readonly id = 'github';\n readonly #client: PlatformApiClient;\n readonly #endpointHost: string;\n readonly #pollingEnabled: boolean;\n readonly #pollingIntervalMs: number | undefined;\n readonly #reconcileEnabled: boolean;\n #storage: SourceControlStorageHandle | undefined;\n #integrationStorage: GithubSubscriptionStorage | undefined;\n /** installationId → cached repository listing (TTL-bounded). */\n readonly #installationReposCache = new Map<number, { repos: RepoSummary[]; expiresAt: number }>();\n /** `orgId:repositoryId` → cached repository access (TTL-bounded). */\n readonly #repositoryAccessCache = new Map<string, { access: RepositoryAccess; expiresAt: number }>();\n readonly #runIssueTriage?: (input: GithubIssueTriageInput) => Promise<GithubIssueTriageResult>;\n\n readonly intake: Intake = {\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: async ({ orgId, userId }) => {\n const installations = await this.#client.request<{\n installations: Array<{\n installationId: number;\n accountLogin: string;\n accountType: string;\n suspendedAt: string | null;\n usable: boolean;\n }>;\n }>('GET', `${API_PREFIX}/github-app/installations`);\n const usable = installations.installations.filter(\n installation => installation.usable && !installation.suspendedAt,\n );\n const repositories = await Promise.all(\n usable.map(async installation => {\n const storedInstallation = await this.versionControl.registerInstallation({\n orgId,\n userId,\n installation: {\n externalId: String(installation.installationId),\n accountName: installation.accountLogin,\n accountType: installation.accountType,\n },\n });\n const result = await this.#client.request<{\n repositories: Array<{\n id: number;\n fullName: string;\n private: boolean;\n defaultBranch: string;\n htmlUrl: string;\n }>;\n }>('GET', `${API_PREFIX}/github-app/installations/${installation.installationId}/repositories`);\n await this.versionControl.registerRepositories({\n orgId,\n installationId: storedInstallation.id,\n repositories: result.repositories.map(repository => ({\n externalId: String(repository.id),\n slug: repository.fullName,\n defaultBranch: repository.defaultBranch,\n metadata: { private: repository.private, url: repository.htmlUrl },\n })),\n });\n return result.repositories.map(repository => ({ repository, installation }));\n }),\n );\n return repositories.flat().map(({ repository, installation }) => ({\n id: repository.fullName,\n name: repository.fullName,\n type: 'repository',\n metadata: {\n installationId: installation.installationId,\n accountLogin: installation.accountLogin,\n accountType: installation.accountType,\n repositoryId: repository.id,\n defaultBranch: repository.defaultBranch,\n private: repository.private,\n url: repository.htmlUrl,\n },\n }));\n },\n listItems: async ({ sourceIds, cursor }) => {\n const page = parsePositiveCursor(cursor);\n const pages = await Promise.all(\n sourceIds.map(async sourceId => {\n const connection = { type: 'app-installation' as const, installationId: 1 };\n const [issues, pullRequests] = await Promise.all([\n this.#listIssues(connection, sourceId, page),\n this.#listPullRequests({ connection, sourceId, includeDrafts: false, cursor: String(page) }),\n ]);\n return {\n items: [\n ...issues.issues.map(issue => ({\n source: { type: 'issue', externalId: `${sourceId}:${issue.id}`, url: issue.url },\n sourceId,\n title: issue.title,\n status: issue.state ?? undefined,\n labels: issue.labels,\n assignee: issue.assignee,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n metadata: { repository: sourceId, number: Number(issue.id), author: issue.author },\n })),\n ...pullRequests.pullRequests.map(pullRequest => ({\n source: { type: 'pull-request', externalId: `${sourceId}:${pullRequest.id}`, url: pullRequest.url },\n sourceId,\n title: pullRequest.title,\n status: pullRequest.state,\n createdAt: pullRequest.createdAt,\n updatedAt: pullRequest.updatedAt,\n metadata: {\n repository: sourceId,\n number: Number(pullRequest.id),\n author: pullRequest.author,\n baseBranch: pullRequest.baseBranch,\n headBranch: pullRequest.headBranch,\n },\n })),\n ],\n hasNextPage: issues.nextCursor !== null || pullRequests.nextCursor !== null,\n };\n }),\n );\n return {\n items: pages.flatMap(result => result.items),\n nextCursor: pages.some(result => result.hasNextPage) ? String(page + 1) : null,\n };\n },\n listIssues: async input => {\n requireGithubConnection(input.connection);\n const sourceId = requireSingleSource(input.sourceIds, 'GitHub Intake requires exactly one repository source.');\n return this.#listIssues(input.connection, sourceId, parsePositiveCursor(input.cursor), input.labels);\n },\n getIssue: input => this.#getIssue(input.connection, input.sourceId, input.issueId),\n createComment: input => this.#createIssueComment(input),\n updateIssue: input => this.#updateIntakeIssue(input),\n };\n\n readonly versionControl: VersionControl = {\n initialize: ({ storage }) => {\n this.#storage = storage;\n },\n registerInstallation: ({ orgId, userId, installation }) =>\n this.storage.installations.upsert({\n orgId,\n connectedByUserId: userId,\n externalId: installation.externalId,\n accountName: installation.accountName,\n accountType: installation.accountType,\n providerMetadata: installation.metadata,\n }),\n registerRepositories: ({ orgId, installationId, repositories }) =>\n Promise.all(\n repositories.map(repository =>\n this.storage.repositories.upsert({\n orgId,\n input: {\n installationId,\n externalId: repository.externalId,\n slug: repository.slug,\n defaultBranch: repository.defaultBranch,\n providerMetadata: repository.metadata,\n },\n }),\n ),\n ),\n getRepositoryAccess: async ({ orgId, repositoryId }) => {\n // Every session materialization requests access; reuse a recent grant\n // instead of re-minting through the Platform each time. The TTL keeps\n // a wide margin under GitHub's ~60min installation-token lifetime.\n const cacheKey = `${orgId}:${repositoryId}`;\n const cached = this.#repositoryAccessCache.get(cacheKey);\n if (cached && cached.expiresAt > Date.now()) return cached.access;\n this.#repositoryAccessCache.delete(cacheKey);\n\n const repository = await this.storage.repositories.get({ orgId, id: repositoryId });\n if (!repository) throw new Error('Version-control repository not found.');\n const cloneUrl = `https://github.com/${repository.slug}.git`;\n const installation = await this.storage.installations.get({ orgId, id: repository.installationId });\n if (!installation) throw new Error('Version-control installation not found.');\n const installationId = parsePositiveInteger(installation.externalId);\n if (installationId === null) throw new Error('GitHub installation id is invalid.');\n const repositoryName = splitRepository(repository.slug).repo;\n\n try {\n const token = await this.#client.request<{ token: string }>(\n 'POST',\n `${API_PREFIX}/github-app/installations/${installationId}/token`,\n { repositories: [repositoryName], permissions: REPOSITORY_TOKEN_PERMISSIONS },\n );\n const access: RepositoryAccess = {\n cloneUrl,\n authorization: { scheme: 'bearer', token: token.token },\n };\n setBounded(this.#repositoryAccessCache, cacheKey, {\n access,\n expiresAt: Date.now() + REPOSITORY_ACCESS_CACHE_TTL_MS,\n });\n return access;\n } catch (err) {\n // Recover from stale installation: when a GitHub App is uninstalled and reinstalled,\n // GitHub assigns a new installation ID. Platform creates a new installation row,\n // and Factory's intake.listSources creates a new local installation row with the\n // new externalId. Try to find the new installation by accountName.\n if (!isNotFound(err) || !installation.accountName) throw err;\n const installations = await this.storage.installations.list({ orgId });\n const newInstallation = installations.find(\n inst => inst.accountName === installation.accountName && inst.id !== installation.id,\n );\n if (!newInstallation) throw err;\n const newInstallationId = parsePositiveInteger(newInstallation.externalId);\n if (newInstallationId === null) throw err;\n\n // Persist the migration so we don't hit the 404 path on every call.\n // This updates the repository's installation_id to the new installation.\n await this.storage.repositories.migrateInstallation({\n orgId,\n id: repositoryId,\n newInstallationId: newInstallation.id,\n });\n\n const token = await this.#client.request<{ token: string }>(\n 'POST',\n `${API_PREFIX}/github-app/installations/${newInstallationId}/token`,\n { repositories: [repositoryName], permissions: REPOSITORY_TOKEN_PERMISSIONS },\n );\n const access: RepositoryAccess = {\n cloneUrl,\n authorization: { scheme: 'bearer', token: token.token },\n };\n setBounded(this.#repositoryAccessCache, cacheKey, {\n access,\n expiresAt: Date.now() + REPOSITORY_ACCESS_CACHE_TTL_MS,\n });\n return access;\n }\n },\n listPullRequests: input => this.#listPullRequests(input),\n getPullRequest: input => this.#getPullRequest(input),\n createPullRequest: input => this.#createPullRequest(input),\n updatePullRequest: input => this.#updatePullRequest(input),\n closePullRequest: input => this.#updatePullRequest({ ...input, state: 'closed' }),\n mergePullRequest: input => this.#mergePullRequest(input),\n listComments: input => this.#listComments(input),\n createComment: input => this.#createComment(input),\n updateComment: input => this.#updateComment(input),\n deleteComment: input => this.#deleteComment(input),\n listReviews: input => this.#listReviews(input),\n getReview: input => this.#getReview(input),\n createReview: input => this.#createReview(input),\n updateReview: input => this.#updateReview(input),\n submitReview: input => this.#submitReview(input),\n dismissReview: input => this.#dismissReview(input),\n deletePendingReview: input => this.#deletePendingReview(input),\n listReviewComments: input => this.#listReviewComments(input),\n createReviewComment: input => this.#createReviewComment(input),\n updateReviewComment: input => this.#updateReviewComment(input),\n deleteReviewComment: input => this.#deleteReviewComment(input),\n listRequestedReviewers: input => this.#requestedReviewers('GET', input),\n requestReviewers: input => this.#requestedReviewers('POST', input),\n removeRequestedReviewers: input => this.#requestedReviewers('DELETE', input),\n };\n\n constructor(\n options: {\n runIssueTriage?: (input: GithubIssueTriageInput) => Promise<GithubIssueTriageResult>;\n } = {},\n ) {\n const config = platformApiClientConfigFromEnv();\n this.#client = new PlatformApiClient(config);\n this.#endpointHost = new URL(config.baseUrl).host;\n this.#pollingEnabled = process.env.MASTRA_PLATFORM_GITHUB_POLLING_ENABLED?.trim().toLowerCase() !== 'false';\n this.#pollingIntervalMs = optionalPositiveIntegerEnv('MASTRA_PLATFORM_GITHUB_POLLING_INTERVAL_MS');\n this.#reconcileEnabled = process.env.MASTRA_PLATFORM_GITHUB_RECONCILE_ENABLED?.trim().toLowerCase() !== 'false';\n this.#runIssueTriage = options.runIssueTriage;\n }\n\n get storage(): SourceControlStorageHandle {\n if (!this.#storage) throw new Error('PlatformGithubIntegration source-control storage has not been initialized.');\n return this.#storage;\n }\n\n get sourceControlStorage(): SourceControlStorageHandle {\n return this.storage;\n }\n\n get integrationStorage(): GithubSubscriptionStorage {\n if (!this.#integrationStorage) {\n throw new Error('PlatformGithubIntegration generic storage has not been initialized.');\n }\n return this.#integrationStorage;\n }\n\n /** Resolve a stored GitHub locator without scanning installations or repositories. */\n async #resolveIntakeDispatch({\n orgId,\n externalSource,\n }: {\n orgId: string;\n externalSource: { type: string; externalId: string };\n }): Promise<{ connection: IntegrationConnection; sourceId: string; issueId: string } | null> {\n const target = parseGithubExternalTarget(externalSource.externalId);\n if (!target) return null;\n const repository = target.repository.includes('/')\n ? target.repository\n : (await this.storage.repositories.findByExternalId({ orgId, externalId: target.repository }))?.slug;\n if (!repository) return null;\n return {\n connection: { type: 'app-installation', installationId: 1 },\n sourceId: repository,\n issueId: target.issueId,\n };\n }\n\n initialize({ storage }: { storage: IntegrationStorageHandle }): void {\n this.#integrationStorage = storage as unknown as GithubSubscriptionStorage;\n logPlatformInfo('Platform GitHub integration initialized', {\n endpointHost: this.#endpointHost,\n pollingEnabled: this.#pollingEnabled,\n pollingIntervalMs: this.#pollingIntervalMs,\n reconcileEnabled: this.#reconcileEnabled,\n });\n }\n\n routes(ctx: IntegrationContext): ApiRoute[] {\n const ingestFactoryEvent = attachGithubRules(this, ctx);\n return [\n this.#statusRoute(ctx),\n this.#connectRoute(ctx),\n this.#connectUserRoute(ctx),\n ...buildGithubRoutes({\n auth: ctx.auth,\n fleet: ctx.fleet,\n storage: ctx.factoryStorage,\n github: this as unknown as GithubIntegration,\n stateSigner: ctx.stateSigner,\n baseUrl: ctx.baseUrl,\n controller: ctx.controller,\n projects: ctx.storage.projects,\n emitAudit: ctx.hooks?.emitAudit,\n ingestFactoryEvent,\n runIssueTriage:\n this.#runIssueTriage ??\n (ctx.controller ? input => runGithubIssueTriage({ controller: ctx.controller!, input }) : undefined),\n }).filter(\n route =>\n route.path !== '/web/github/status' &&\n route.path !== '/web/github/webhook' &&\n !route.path.startsWith('/auth/github/'),\n ),\n ];\n }\n\n #statusRoute(ctx: IntegrationContext): ApiRoute {\n return registerApiRoute('/web/github/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await ctx.auth.ensureUser(loose(c));\n const tenant = ctx.auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n sandboxEnabled: ctx.fleet.enabled,\n organizationRequired: true,\n connected: false,\n installations: [],\n userConnected: false,\n userGithubUsername: null,\n reason: 'organization_required',\n diagnostics: this.diagnostics(),\n });\n }\n\n const [installations, userConnection] = await Promise.all([\n this.#syncInstallations(tenant.orgId, tenant.userId),\n this.#fetchUserConnection(tenant.userId),\n ]);\n return c.json({\n enabled: true,\n sandboxEnabled: ctx.fleet.enabled,\n connected: installations.length > 0,\n installations: installations.map(installation => ({\n installationId: Number(installation.externalId),\n accountLogin: installation.accountName,\n accountType: installation.accountType,\n })),\n userConnected: userConnection.connected,\n userGithubUsername: userConnection.githubUsername,\n reason: installations.length > 0 ? 'ready' : 'not_connected',\n diagnostics: this.diagnostics(),\n });\n },\n });\n }\n\n #connectRoute(ctx: IntegrationContext): ApiRoute {\n return registerApiRoute('/auth/github/connect', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await ctx.auth.ensureUser(loose(c));\n const tenant = ctx.auth.tenant(loose(c));\n if (!tenant?.orgId) return c.json({ error: 'unauthorized' }, 401);\n\n const redirectTo = c.req.query('redirectTo') || c.req.query('return_to') || '/';\n const originator = routeBaseUrl(ctx, c.req.url);\n logPlatformInfo('Starting Platform GitHub connect flow', {\n orgId: tenant.orgId,\n redirectTo,\n originator,\n });\n const query = new URLSearchParams({\n action: 'install',\n redirectTo,\n originator,\n });\n const { url } = await this.#client.request<{ url: string }>(\n 'GET',\n `${API_PREFIX}/github-app/install-url?${query}`,\n );\n return c.redirect(url);\n },\n });\n }\n\n #connectUserRoute(ctx: IntegrationContext): ApiRoute {\n return registerApiRoute('/auth/github/connect-user', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await ctx.auth.ensureUser(loose(c));\n const tenant = ctx.auth.tenant(loose(c));\n if (!tenant?.orgId) return c.json({ error: 'unauthorized' }, 401);\n\n const redirectTo = c.req.query('redirectTo') || c.req.query('return_to') || '/';\n const originator = routeBaseUrl(ctx, c.req.url);\n logPlatformInfo('Starting Platform GitHub user authorization flow', {\n orgId: tenant.orgId,\n redirectTo,\n originator,\n });\n const query = new URLSearchParams({\n userId: tenant.userId,\n redirectTo,\n originator,\n });\n const { url } = await this.#client.request<{ url: string }>(\n 'GET',\n `${API_PREFIX}/github-app/authenticate?${query}`,\n );\n return c.redirect(url);\n },\n });\n }\n\n /**\n * Personal GitHub connection status for the acting user. Returns\n * not-connected when the platform predates the user-connection endpoint.\n */\n async #fetchUserConnection(userId: string): Promise<PlatformGithubUserConnection> {\n try {\n const connection = await this.#client.request<PlatformGithubUserConnection>(\n 'GET',\n `${API_PREFIX}/github-app/user-connection?${new URLSearchParams({ userId })}`,\n );\n if (!connection.connected && connection.reason) {\n logPlatformWarn('Platform GitHub user connection verification failed', {\n userId,\n reason: connection.reason,\n });\n }\n return connection;\n } catch {\n return { connected: false, githubUsername: null };\n }\n }\n\n async #syncInstallations(orgId: string, userId: string): Promise<SourceControlInstallation[]> {\n const result = await this.#client.request<{ installations: PlatformGithubInstallation[] }>(\n 'GET',\n `${API_PREFIX}/github-app/installations`,\n );\n const usableInstallations = result.installations.filter(\n installation => installation.usable && !installation.suspendedAt,\n );\n return Promise.all(\n usableInstallations.map(installation =>\n this.versionControl.registerInstallation({\n orgId,\n userId,\n installation: {\n externalId: String(installation.installationId),\n accountName: installation.accountLogin,\n accountType: installation.accountType,\n },\n }),\n ),\n );\n }\n\n workers(ctx: IntegrationContext): PlatformGithubEventWorker[] {\n if (!this.#pollingEnabled && !this.#reconcileEnabled) return [];\n if (!ctx.controller) {\n throw new Error('Platform GitHub event polling requires the mounted Mastra Code controller.');\n }\n return [\n new PlatformGithubEventWorker({\n client: this.#client,\n controller: ctx.controller,\n github: this,\n storage: ctx.storage.generic as unknown as PlatformGithubEventStorage,\n ingestFactoryEvent: attachGithubRules(this, ctx),\n reconcileFactoryState: this.#reconcileEnabled\n ? attachGithubReconciler(this, ctx, input => this.fetchPullRequestState(input))\n : undefined,\n pollEventsEnabled: this.#pollingEnabled,\n intervalMs: this.#pollingIntervalMs,\n }),\n ];\n }\n\n /**\n * Reads live PR state through the Platform GitHub proxy for the merge\n * reconciler. Returns undefined when the PR cannot be resolved (missing,\n * proxy error) so a sweep never fabricates a merge.\n */\n async fetchPullRequestState(input: {\n installationId: number;\n repository: string;\n number: number;\n }): Promise<ReconcilePullRequestState | undefined> {\n let repository: { owner: string; repo: string };\n try {\n repository = splitRepository(input.repository);\n } catch {\n return undefined;\n }\n try {\n const result = await this.#client.request<{\n title?: string;\n html_url?: string;\n state?: string;\n merged?: boolean;\n created_at?: string;\n merged_by?: { login?: string } | null;\n head?: { ref?: string };\n base?: { ref?: string };\n }>(\n 'GET',\n `${API_PREFIX}/github/repos/${encodeURIComponent(repository.owner)}/${encodeURIComponent(repository.repo)}/pulls/${input.number}`,\n );\n return {\n title: result.title ?? `PR ${input.number}`,\n url: result.html_url ?? `https://github.com/${input.repository}/pull/${input.number}`,\n state: result.state === 'closed' ? 'closed' : 'open',\n merged: result.merged === true,\n headBranch: result.head?.ref ?? '',\n baseBranch: result.base?.ref ?? '',\n ...(result.created_at ? { createdAt: result.created_at } : {}),\n ...(result.merged_by?.login ? { mergedBy: result.merged_by.login } : {}),\n };\n } catch {\n return undefined;\n }\n }\n\n sessionTools({ requestContext }: { requestContext: RequestContext }): IntegrationTools {\n return createGithubSubscriptionTools(requestContext, this as unknown as GithubIntegration);\n }\n\n async postToolObserver({\n toolContext,\n requestContext,\n }: Parameters<NonNullable<FactoryIntegration['postToolObserver']>>[0]): Promise<void> {\n const pullRequestUrl = parseCreatedPullRequest(toolContext);\n if (!pullRequestUrl || !requestContext) return;\n await subscribeCurrentSessionToPullRequest(\n requestContext,\n pullRequestUrl,\n 'auto-gh-pr-create',\n this as unknown as GithubIntegration,\n );\n }\n\n diagnostics(): Record<string, unknown> {\n return {\n mode: 'platform',\n endpointHost: this.#endpointHost,\n polling: {\n enabled: this.#pollingEnabled,\n ...(this.#pollingIntervalMs === undefined ? {} : { intervalMs: this.#pollingIntervalMs }),\n },\n reconcile: { enabled: this.#reconcileEnabled },\n };\n }\n\n async getRepositoryCollaboratorPermission(\n _installationId: number,\n repoFullName: string,\n username: string,\n signal?: AbortSignal,\n ): Promise<GithubRepositoryPermission | undefined> {\n let repository: { owner: string; repo: string };\n try {\n repository = splitRepository(repoFullName);\n } catch {\n return undefined;\n }\n try {\n const result = await this.#client.request<{ permission: GithubRepositoryPermission }>(\n 'GET',\n `${API_PREFIX}/github/repos/${encodeURIComponent(repository.owner)}/${encodeURIComponent(repository.repo)}/collaborators/${encodeURIComponent(username)}/permission`,\n undefined,\n { signal },\n );\n return result.permission;\n } catch {\n return undefined;\n }\n }\n\n async listInstallationRepos(installationId: number): Promise<RepoSummary[]> {\n // Hot in two places — the repos route and token minting (which re-lists\n // only to validate the 1–10 repo rule). A short TTL collapses repeat\n // Platform round trips within one UI interaction.\n const cached = this.#installationReposCache.get(installationId);\n if (cached && cached.expiresAt > Date.now()) return cached.repos;\n this.#installationReposCache.delete(installationId);\n\n const result = await this.#client.request<{\n repositories: Array<{\n id: number;\n owner: string;\n name: string;\n fullName: string;\n private: boolean;\n defaultBranch: string;\n }>;\n }>('GET', `${API_PREFIX}/github-app/installations/${installationId}/repositories`);\n const repos = result.repositories.map(repository => ({ ...repository, installationId }));\n setBounded(this.#installationReposCache, installationId, {\n repos,\n expiresAt: Date.now() + INSTALLATION_REPOS_CACHE_TTL_MS,\n });\n return repos;\n }\n\n async mintInstallationToken(installationId: number): Promise<string> {\n const repositories = await this.listInstallationRepos(installationId);\n if (repositories.length === 0 || repositories.length > 10) {\n throw new Error('Platform GitHub token minting requires between one and ten installation repositories.');\n }\n const result = await this.#client.request<{ token: string }>(\n 'POST',\n `${API_PREFIX}/github-app/installations/${installationId}/token`,\n { repositories: repositories.map(repository => repository.name), permissions: REPOSITORY_TOKEN_PERMISSIONS },\n );\n return result.token;\n }\n\n async addIssueLabels(\n _installationId: number,\n sourceId: string,\n issueNumber: number,\n labels: string[],\n ): Promise<string[]> {\n const result = await this.#client.request<{ labels: string[] }>(\n 'POST',\n repositoryPath(sourceId, `issues/${issueNumber}/labels`),\n { labels },\n );\n return result.labels;\n }\n\n getInstallationOctokit(_installationId: number): ReturnType<GithubIntegration['getInstallationOctokit']> {\n return {\n pulls: {\n get: async ({ owner, repo, pull_number }: { owner: string; repo: string; pull_number: number }) => {\n const data = await this.#client.request<GithubPullRequest>(\n 'GET',\n repositoryPath(`${owner}/${repo}`, `pulls/${pull_number}`),\n );\n return { data: { base: { repo: { id: data.base.repo.id } } } };\n },\n },\n } as unknown as ReturnType<GithubIntegration['getInstallationOctokit']>;\n }\n\n async #listIssues(connection: IntegrationConnection, sourceId: string, page: number, labels?: string[]) {\n requireGithubConnection(connection);\n const path = repositoryPath(sourceId, 'issues');\n const query = new URLSearchParams({ state: 'open', page: String(page), per_page: String(PAGE_SIZE) });\n const normalizedLabels = normalizeLabels(labels);\n if (normalizedLabels.length > 0) query.set('label', normalizedLabels.join(','));\n const result = await this.#client.request<{ issues: GithubIssue[] }>('GET', `${path}?${query}`);\n return {\n issues: result.issues.map(issue => parseIntakeIssue(sourceId, issue)),\n nextCursor: result.issues.length === PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #getIssue(connection: IntegrationConnection, sourceId: string | undefined, issueId: string) {\n requireGithubConnection(connection);\n const repository = requireSource(sourceId, 'GitHub Intake requires a repository source.');\n const issueNumber = requirePositiveId(issueId, 'issue');\n try {\n const [issue, comments] = await Promise.all([\n this.#client.request<GithubIssue>('GET', repositoryPath(repository, `issues/${issueNumber}`)),\n this.#client.request<{ comments: GithubComment[] }>(\n 'GET',\n `${repositoryPath(repository, `issues/${issueNumber}/comments`)}?per_page=100`,\n ),\n ]);\n return parseIntakeIssueDetail(repository, issue, comments.comments);\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n async #updateIntakeIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> {\n requireGithubConnection(input.connection);\n const repository = requireSource(input.sourceId, 'GitHub Intake requires a repository source.');\n const issueNumber = requirePositiveId(input.issueId, 'issue');\n if (input.state.kind === 'byName') {\n logPlatformWarn(`Platform GitHub: updateIssue byName is not supported (name=${input.state.name}); ignoring.`);\n return null;\n }\n const targetState: 'open' | 'closed' =\n input.state.stateType === 'unstarted' || input.state.stateType === 'started' ? 'open' : 'closed';\n const stateReason: 'completed' | 'not_planned' | null =\n targetState === 'closed' ? (input.state.stateType === 'canceled' ? 'not_planned' : 'completed') : null;\n // Reject PR targets: probe the pulls endpoint. A 200 means the number is a\n // pull request, not an issue. Factory does not close PRs via updateIssue —\n // PR merges/closes go through the version-control pipeline.\n try {\n await this.#client.request<GithubPullRequest>('GET', repositoryPath(repository, `pulls/${issueNumber}`));\n logPlatformWarn(`Platform GitHub: updateIssue rejected — target ${repository}#${issueNumber} is a pull request.`);\n return null;\n } catch (error) {\n if (!isNotFound(error)) throw error;\n // 404 on pulls means it's an issue (or nothing) — fall through to PATCH.\n }\n try {\n const issue = await this.#client.request<GithubIssue>(\n 'PATCH',\n repositoryPath(repository, `issues/${issueNumber}`),\n {\n state: targetState,\n ...(stateReason ? { state_reason: stateReason } : {}),\n },\n { actingUserId: input.actingUserId },\n );\n return parseIntakeIssue(repository, issue);\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n async #createIssueComment(input: CreateIntakeCommentInput) {\n requireGithubConnection(input.connection);\n const repository = requireSource(input.sourceId, 'GitHub Intake requires a repository source.');\n const issueNumber = requirePositiveId(input.issueId, 'issue');\n try {\n const comment = await this.#client.request<GithubComment>(\n 'POST',\n repositoryPath(repository, `issues/${issueNumber}/comments`),\n { body: input.body },\n { actingUserId: input.actingUserId },\n );\n return { id: String(comment.id), url: comment.htmlUrl };\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n async #listPullRequests(input: ListPullRequestsInput) {\n requireGithubConnection(input.connection);\n const page = parsePositiveCursor(input.cursor);\n const query = new URLSearchParams({\n state: input.state ?? 'open',\n page: String(page),\n per_page: String(PAGE_SIZE),\n });\n const result = await this.#client.request<{ pullRequests: GithubPullRequest[] }>(\n 'GET',\n `${repositoryPath(input.sourceId, 'pulls')}?${query}`,\n );\n return {\n pullRequests: result.pullRequests\n .filter(pullRequest => input.includeDrafts !== false || !pullRequest.draft)\n .map(parsePullRequest),\n nextCursor: result.pullRequests.length === PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #getPullRequest(input: PullRequestRef) {\n try {\n return parsePullRequest(\n await this.#client.request<GithubPullRequest>('GET', pullRequestPath(input, input.pullRequestId)),\n );\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n async #createPullRequest(input: CreatePullRequestInput) {\n requireGithubConnection(input.connection);\n const result = await this.#client.request<GithubPullRequest>(\n 'POST',\n repositoryPath(input.sourceId, 'pulls'),\n {\n head: input.headBranch,\n base: input.baseBranch,\n title: input.title,\n body: input.body,\n draft: input.draft,\n },\n { actingUserId: input.actingUserId },\n );\n return parsePullRequest(result);\n }\n\n async #updatePullRequest(input: UpdatePullRequestInput) {\n const result = await this.#client.request<GithubPullRequest>(\n 'PATCH',\n pullRequestPath(input, input.pullRequestId),\n {\n title: input.title,\n body: input.body === null ? '' : input.body,\n base: input.baseBranch,\n state: input.state,\n },\n { actingUserId: input.actingUserId },\n );\n return parsePullRequest(result);\n }\n\n #mergePullRequest(input: MergePullRequestInput) {\n return this.#client.request<{ merged: boolean; message: string; sha: string | null }>(\n 'PUT',\n `${pullRequestPath(input, input.pullRequestId)}/merge`,\n { commitTitle: input.commitTitle, commitMessage: input.commitMessage, method: input.method },\n { actingUserId: input.actingUserId },\n );\n }\n\n async #listComments(input: ListPullRequestCommentsInput) {\n const page = parsePositiveCursor(input.cursor);\n const result = await this.#client.request<{ comments: GithubComment[] }>(\n 'GET',\n `${repositoryPath(input.sourceId, `issues/${requirePositiveId(input.pullRequestId, 'pull request')}/comments`)}?page=${page}&per_page=${PAGE_SIZE}`,\n );\n return {\n comments: result.comments.map(parseComment),\n nextCursor: result.comments.length === PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #createComment(input: CreatePullRequestCommentInput) {\n const comment = await this.#client.request<GithubComment>(\n 'POST',\n repositoryPath(input.sourceId, `issues/${requirePositiveId(input.pullRequestId, 'pull request')}/comments`),\n { body: input.body },\n { actingUserId: input.actingUserId },\n );\n return parseComment(comment);\n }\n\n async #updateComment(input: UpdatePullRequestCommentInput) {\n requireGithubConnection(input.connection);\n const comment = await this.#client.request<GithubComment>(\n 'PATCH',\n repositoryPath(input.sourceId, `issues/comments/${requirePositiveId(input.commentId, 'comment')}`),\n { body: input.body },\n { actingUserId: input.actingUserId },\n );\n return parseComment(comment);\n }\n\n async #deleteComment(input: DeletePullRequestCommentInput) {\n requireGithubConnection(input.connection);\n await this.#client.request<void>(\n 'DELETE',\n repositoryPath(input.sourceId, `issues/comments/${requirePositiveId(input.commentId, 'comment')}`),\n undefined,\n { actingUserId: input.actingUserId },\n );\n }\n\n async #listReviews(input: ListReviewsInput) {\n const page = parsePositiveCursor(input.cursor);\n const result = await this.#client.request<{ reviews: GithubReview[] }>(\n 'GET',\n `${pullRequestPath(input, input.pullRequestId)}/reviews?page=${page}&per_page=${PAGE_SIZE}`,\n );\n return {\n reviews: result.reviews.map(parseReview),\n nextCursor: result.reviews.length === PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #getReview(input: ReviewRef) {\n try {\n return parseReview(\n await this.#client.request<GithubReview>(\n 'GET',\n `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, 'review')}`,\n ),\n );\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n async #createReview(input: CreateReviewInput) {\n const review = await this.#client.request<GithubReview>(\n 'POST',\n `${pullRequestPath(input, input.pullRequestId)}/reviews`,\n { body: input.body, commitId: input.commitId, event: input.event ? reviewEvent(input.event) : undefined },\n { actingUserId: input.actingUserId },\n );\n return parseReview(review);\n }\n\n async #updateReview(input: UpdateReviewInput) {\n const review = await this.#client.request<GithubReview>(\n 'PUT',\n `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, 'review')}`,\n { body: input.body },\n { actingUserId: input.actingUserId },\n );\n return parseReview(review);\n }\n\n async #submitReview(input: SubmitReviewInput) {\n const review = await this.#client.request<GithubReview>(\n 'POST',\n `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, 'review')}/events`,\n { body: input.body, event: reviewEvent(input.event) },\n { actingUserId: input.actingUserId },\n );\n return parseReview(review);\n }\n\n async #dismissReview(input: DismissReviewInput) {\n const review = await this.#client.request<GithubReview>(\n 'PUT',\n `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, 'review')}/dismissals`,\n { message: input.message },\n { actingUserId: input.actingUserId },\n );\n return parseReview(review);\n }\n\n async #deletePendingReview(input: ReviewRef) {\n await this.#client.request<void>(\n 'DELETE',\n `${pullRequestPath(input, input.pullRequestId)}/reviews/${requirePositiveId(input.reviewId, 'review')}`,\n undefined,\n { actingUserId: input.actingUserId },\n );\n }\n\n async #listReviewComments(input: ListReviewCommentsInput) {\n const page = parsePositiveCursor(input.cursor);\n const result = await this.#client.request<{ comments: GithubReviewComment[] }>(\n 'GET',\n `${pullRequestPath(input, input.pullRequestId)}/comments?page=${page}&per_page=${PAGE_SIZE}`,\n );\n return {\n comments: result.comments.map(parseReviewComment),\n nextCursor: result.comments.length === PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #createReviewComment(input: CreateReviewCommentInput) {\n let body: Record<string, unknown>;\n if (input.replyToId !== undefined) {\n body = { body: input.body, replyToId: requirePositiveId(input.replyToId, 'review comment') };\n } else {\n if (!input.commitId || !input.path || input.line === undefined || !input.side) {\n throw new Error('A review comment requires commitId, path, line, and side unless it is a reply.');\n }\n body = {\n body: input.body,\n commitId: input.commitId,\n path: input.path,\n line: input.line,\n side: input.side.toUpperCase(),\n startLine: input.startLine,\n startSide: input.startSide?.toUpperCase(),\n };\n }\n return parseReviewComment(\n await this.#client.request<GithubReviewComment>(\n 'POST',\n `${pullRequestPath(input, input.pullRequestId)}/comments`,\n body,\n { actingUserId: input.actingUserId },\n ),\n );\n }\n\n async #updateReviewComment(input: UpdatePullRequestCommentInput) {\n requireGithubConnection(input.connection);\n return parseReviewComment(\n await this.#client.request<GithubReviewComment>(\n 'PATCH',\n repositoryPath(input.sourceId, `pulls/comments/${requirePositiveId(input.commentId, 'review comment')}`),\n { body: input.body },\n { actingUserId: input.actingUserId },\n ),\n );\n }\n\n async #deleteReviewComment(input: DeletePullRequestCommentInput) {\n requireGithubConnection(input.connection);\n await this.#client.request<void>(\n 'DELETE',\n repositoryPath(input.sourceId, `pulls/comments/${requirePositiveId(input.commentId, 'review comment')}`),\n undefined,\n { actingUserId: input.actingUserId },\n );\n }\n\n #requestedReviewers(method: 'GET' | 'POST' | 'DELETE', input: UpdateReviewersInput) {\n requireGithubConnection(input.connection);\n return this.#client.request<{ users: string[]; teams: string[] }>(\n method,\n `${pullRequestPath(input, input.pullRequestId)}/requested-reviewers`,\n method === 'GET' ? undefined : { users: input.users, teams: input.teams },\n method === 'GET' ? undefined : { actingUserId: input.actingUserId },\n );\n }\n}\n\nfunction repositoryPath(sourceId: string, suffix: string): string {\n const { owner, repo } = splitRepository(sourceId);\n return `${API_PREFIX}/github/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${suffix}`;\n}\n\nfunction pullRequestPath(\n input: { connection: IntegrationConnection; sourceId: string },\n pullRequestId: string,\n): string {\n requireGithubConnection(input.connection);\n return repositoryPath(input.sourceId, `pulls/${requirePositiveId(pullRequestId, 'pull request')}`);\n}\n\nfunction splitRepository(sourceId: string): { owner: string; repo: string } {\n const slash = sourceId.indexOf('/');\n if (slash <= 0 || slash === sourceId.length - 1) {\n throw new Error('GitHub capabilities require an owner/repository source.');\n }\n return { owner: sourceId.slice(0, slash), repo: sourceId.slice(slash + 1) };\n}\n\nfunction parseIntakeIssue(sourceId: string, issue: GithubIssue): IntakeIssue {\n return {\n id: String(issue.number),\n identifier: `#${issue.number}`,\n title: issue.title,\n url: issue.htmlUrl,\n author: issue.user?.login ?? null,\n state: issue.state,\n stateType: issue.state,\n priority: null,\n assignee: issue.assignees[0] ?? null,\n source: sourceId,\n labels: issue.labels,\n commentCount: issue.commentCount,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\nfunction parseIntakeIssueDetail(sourceId: string, issue: GithubIssue, comments: GithubComment[]): IntakeIssueDetail {\n return {\n ...parseIntakeIssue(sourceId, issue),\n description: issue.body?.trim() ? issue.body : null,\n comments: comments.map(comment => ({\n author: comment.user?.login ?? null,\n body: comment.body,\n createdAt: comment.createdAt,\n })),\n };\n}\n\nfunction parsePullRequest(pullRequest: GithubPullRequest): PullRequest {\n return {\n id: String(pullRequest.number),\n title: pullRequest.title,\n url: pullRequest.htmlUrl,\n author: pullRequest.user?.login ?? null,\n body: pullRequest.body?.trim() ? pullRequest.body : null,\n state: pullRequest.state,\n draft: pullRequest.draft,\n merged: pullRequest.merged,\n mergeable: pullRequest.mergeable,\n baseBranch: pullRequest.base.ref,\n headBranch: pullRequest.head.ref,\n headSha: pullRequest.head.sha,\n createdAt: pullRequest.createdAt,\n updatedAt: pullRequest.updatedAt,\n };\n}\n\nfunction parseComment(comment: GithubComment): PullRequestComment {\n return {\n id: String(comment.id),\n url: comment.htmlUrl,\n author: comment.user?.login ?? null,\n body: comment.body,\n createdAt: comment.createdAt,\n updatedAt: comment.updatedAt,\n };\n}\n\nfunction parseReview(review: GithubReview): Review {\n const states: Record<GithubReview['state'], Review['state']> = {\n PENDING: 'pending',\n COMMENTED: 'commented',\n APPROVED: 'approved',\n CHANGES_REQUESTED: 'changes-requested',\n DISMISSED: 'dismissed',\n };\n return {\n id: String(review.id),\n url: review.htmlUrl,\n author: review.user?.login ?? null,\n body: review.body?.trim() ? review.body : null,\n state: states[review.state],\n commitId: review.commitId,\n submittedAt: review.submittedAt,\n };\n}\n\nfunction parseReviewComment(comment: GithubReviewComment): ReviewComment {\n return {\n ...parseComment(comment),\n path: comment.path,\n line: comment.line,\n side: comment.side?.toLowerCase() as 'left' | 'right' | null,\n commitId: comment.commitId,\n replyToId: comment.replyToId === null ? null : String(comment.replyToId),\n };\n}\n\nfunction requireGithubConnection(connection: IntegrationConnection): void {\n if (connection.type !== 'app-installation' && connection.type !== 'oauth') {\n throw new Error('GitHub capabilities require a GitHub connection.');\n }\n}\n\nfunction requireSingleSource(sourceIds: string[], message: string): string {\n if (sourceIds.length !== 1) throw new Error(message);\n return sourceIds[0]!;\n}\n\nfunction requireSource(sourceId: string | undefined, message: string): string {\n if (!sourceId) throw new Error(message);\n return sourceId;\n}\n\nfunction normalizeLabels(labels: string[] | undefined): string[] {\n return [...new Set((labels ?? []).map(label => label.trim()).filter(Boolean))];\n}\n\nfunction parsePositiveCursor(cursor: string | undefined): number {\n if (cursor === undefined) return 1;\n const parsed = parsePositiveInteger(cursor);\n if (parsed === null) throw new Error('GitHub cursor must be a positive page number.');\n return parsed;\n}\n\nfunction parsePositiveInteger(value: string): number | null {\n if (!/^\\d+$/.test(value)) return null;\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;\n}\n\nfunction parseGithubExternalTarget(externalId: string): { repository: string; issueId: string } | null {\n const match =\n externalId.match(/^(.+\\/.+):(\\d+)$/) ??\n externalId.match(/^github:(\\d+):(?:issue|pull-request):(\\d+)$/) ??\n externalId.match(/^(\\d+):(\\d+)$/);\n if (!match?.[1] || !match[2] || parsePositiveInteger(match[2]) === null) return null;\n return { repository: match[1], issueId: match[2] };\n}\n\nfunction optionalPositiveIntegerEnv(name: 'MASTRA_PLATFORM_GITHUB_POLLING_INTERVAL_MS'): number | undefined {\n const value = process.env[name]?.trim();\n if (!value) return undefined;\n const parsed = parsePositiveInteger(value);\n if (parsed === null) throw new Error(`${name} must be a positive integer.`);\n return parsed;\n}\n\nfunction requirePositiveId(value: string, resource: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed === null) throw new Error(`GitHub ${resource} id must be a positive integer.`);\n return parsed;\n}\n\nfunction reviewEvent(event: 'approve' | 'request-changes' | 'comment') {\n if (event === 'approve') return 'APPROVE' as const;\n if (event === 'request-changes') return 'REQUEST_CHANGES' as const;\n return 'COMMENT' as const;\n}\n\nfunction isNotFound(error: unknown): boolean {\n return error instanceof PlatformApiError && error.status === 404;\n}\n"],"mappings":";;;;;;;;AA4IA,MAAM,YAAY;AAClB,MAAM,aAAa;;;;;;AAMnB,MAAM,kCAAkC;;;;;;AAMxC,MAAM,iCAAiC,IAAI;;;;;;;AAO3C,MAAM,oBAAoB;AAE1B,SAAS,WAAiB,OAAkB,KAAQ,OAAgB;CAClE,MAAM,OAAO,GAAG;CAChB,MAAM,IAAI,KAAK,KAAK;CACpB,IAAI,MAAM,OAAO,mBAAmB;EAClC,MAAM,SAAS,MAAM,KAAK,CAAC,CAAC,KAA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A;CACnB,MAAM,SAAS,qBAAqB,KAAK;CACzC,IAAI,WAAW,MAAM,MAAM,IAAI,MAAM,GAAG,KAAK,6BAA6B;CAC1E,OAAO;AACT;AAEA,SAAS,kBAAkB,OAAe,UAA0B;CAClE,MAAM,SAAS,qBAAqB,KAAK;CACzC,IAAI,WAAW,MAAM,MAAM,IAAI,MAAM,UAAU,SAAS,gCAAgC;CACxF,OAAO;AACT;AAEA,SAAS,YAAY,OAAkD;CACrE,IAAI,UAAU,WAAW,OAAO;CAChC,IAAI,UAAU,mBAAmB,OAAO;CACxC,OAAO;AACT;AAEA,SAAS,WAAW,OAAyB;CAC3C,OAAO,iBAAiB,oBAAoB,MAAM,WAAW;AAC/D"}
@@ -10,6 +10,7 @@ import type { FactoryRules } from '../rules/types.js';
10
10
  import type { SandboxFleet } from '../sandbox/fleet.js';
11
11
  import type { StateSigner } from '../state-signing.js';
12
12
  import type { AuditEmitter } from '../storage/domains/audit/domain.js';
13
+ import type { ChannelIdentityStorage } from '../storage/domains/channel-identity/base.js';
13
14
  import type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';
14
15
  import type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';
15
16
  import type { IntakeStorage } from '../storage/domains/intake/base.js';
@@ -52,6 +53,7 @@ export interface FactoryApiRoutesDeps {
52
53
  projects: FactoryProjectsStorage;
53
54
  queueHealth: QueueHealthStorage;
54
55
  workItems: WorkItemsStorage;
56
+ channelIdentity: ChannelIdentityStorage;
55
57
  };
56
58
  integrations?: IntegrationRegistration[];
57
59
  intakeReady: boolean;
@@ -76,7 +78,7 @@ export declare function buildIntegrationContext(deps: Pick<FactoryApiRoutesDeps,
76
78
  emitAudit?: AuditEmitter['emit'];
77
79
  rules: FactoryRules;
78
80
  factoryReady: boolean;
79
- domains: Pick<FactoryApiRoutesDeps['domains'], 'projects' | 'intake' | 'workItems'>;
81
+ domains: Pick<FactoryApiRoutesDeps['domains'], 'projects' | 'intake' | 'workItems' | 'channelIdentity'>;
80
82
  }, integrationId: string): IntegrationContext;
81
83
  /**
82
84
  * Assemble the custom `/web/*` API routes as Mastra `server.apiRoutes`:
@@ -1 +1 @@
1
- {"version":3,"file":"surface.d.ts","sourceRoot":"","sources":["../../src/routes/surface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAItF,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,wBAAwB,CAAC;AAE7E,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACtF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6CAA6C,CAAC;AAC1F,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAClF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AACxF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wCAAwC,CAAC;AACh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gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE;QAC3B,iBAAiB,EAAE,wBAAwB,CAAC;QAC5C,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,8BAA8B,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KAC3E,KAAK,IAAI,CAAC;CACZ;AAiDD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,8BAA8B,CAAC,MAAM,CAAC,GAAG,MAAM,CAmBtF;AA2CD;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,IAAI,CACR,oBAAoB,EACpB,YAAY,GAAG,cAAc,GAAG,MAAM,GAAG,OAAO,GAAG,gBAAgB,GAAG,oBAAoB,GAAG,sBAAsB,CACpH,GAAG;IACF,WAAW,EAAE,WAAW,CAAC;IACzB,SAAS,CAAC,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;IACjC,KAAK,EAAE,YAAY,CAAC;IACpB,YAAY,EAAE,OAAO,CAAC;IACtB,OAAO,EAAE,IAAI,CAAC,oBAAoB,CAAC,SAAS,CAAC,EAAE,UAAU,GAAG,QAAQ,GAAG,WAAW,GAAG,iBAAiB,CAAC,CAAC;CACzG,EACD,aAAa,EAAE,MAAM,GACpB,kBAAkB,CAkBpB;AAsDD;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,oBAAoB,GAAG,QAAQ,EAAE,CAoG/E"}
@@ -112,7 +112,8 @@ function buildIntegrationContext(deps, integrationId) {
112
112
  generic: deps.integrationStorage.forIntegration(integrationId),
113
113
  sourceControl: deps.sourceControlStorage.forIntegration(integrationId),
114
114
  projects: deps.domains.projects,
115
- intake: deps.domains.intake
115
+ intake: deps.domains.intake,
116
+ channelIdentity: deps.domains.channelIdentity
116
117
  },
117
118
  ...deps.factoryReady ? { rules: {
118
119
  config: deps.rules,
@@ -1 +1 @@
1
- {"version":3,"file":"surface.js","names":[],"sources":["../../src/routes/surface.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { FactoryStorage } from '@mastra/core/storage';\n\nimport type { FactoryIntegration, IntegrationContext } from '../integrations/base.js';\nimport { getGithubFeatureDiagnostics } from '../integrations/github/config.js';\nimport { ensureFactoryRuleSession } from '../integrations/github/factory-session.js';\nimport type { GithubIntegration } from '../integrations/github/integration.js';\nimport type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';\nimport { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { FactoryTransitionService } from '../rules/transition-service.js';\nimport type { FactoryRules } from '../rules/types.js';\nimport type { SandboxFleet } from '../sandbox/fleet.js';\nimport type { StateSigner } from '../state-signing.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { IntegrationStorage } from '../storage/domains/integrations/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { ModelPacksStorage } from '../storage/domains/model-packs/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport type { SourceControlStorage } from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { ConfigRoutes } from './config.js';\nimport { invalidateCustomProvidersSnapshots } from './custom-provider-source.js';\nimport { buildFsRoutes } from './fs.js';\nimport { IntakeRoutes } from './intake.js';\nimport { OAuthRoutes } from './oauth.js';\nimport type { RouteAuth } from './route.js';\nimport { SkillRoutes } from './skills.js';\nimport { invalidateTenantCredentialSnapshots } from './tenant-credentials.js';\nimport { WorkItemRoutes } from './work-items.js';\n\nexport interface IntegrationRegistration {\n integration: FactoryIntegration;\n ready: boolean;\n ensureReady: () => Promise<void>;\n}\n\nexport interface FactoryApiRoutesDeps {\n controllerId: string;\n controller: AgentController<MastraCodeState>;\n /** Request-auth seam threaded from the host (no service locator). */\n auth: RouteAuth;\n authStorage: AuthStorage;\n audit: AuditEmitter;\n fsRoot?: string;\n publicOrigin: string;\n stateSigner?: StateSigner;\n /** Sandbox fleet constructed by the factory (disabled when no machine). */\n fleet: SandboxFleet;\n /** Root factory storage backend (distributed locks, app-db diagnostics). */\n factoryStorage?: FactoryStorage;\n integrationStorage: IntegrationStorage;\n sourceControlStorage: SourceControlStorage;\n /** App-table domain handles, registered and owned by `MastraFactory.prepare()`. */\n domains: {\n intake: IntakeStorage;\n modelCredentials: ModelCredentialsStorage;\n memorySettings: MemorySettingsStorage;\n customProviders: CustomProvidersStorage;\n modelPacks: ModelPacksStorage;\n projects: FactoryProjectsStorage;\n queueHealth: QueueHealthStorage;\n workItems: WorkItemsStorage;\n };\n integrations?: IntegrationRegistration[];\n intakeReady: boolean;\n factoryReady: boolean;\n /** Resolved Factory rule set, threaded from the host (no service locator). */\n rules: FactoryRules;\n factoryTransitionService?: FactoryTransitionService;\n onFactoryRuntime?: (runtime: {\n transitionService: FactoryTransitionService;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n }) => void;\n}\n\nfunction guardIntegrationRoutes({\n integration,\n ready,\n ensureReady,\n routes,\n}: IntegrationRegistration & { routes: ApiRoute[] }): ApiRoute[] {\n if (ready) return routes;\n return routes.map(route => {\n if ('handler' in route) {\n const handler = route.handler;\n return {\n ...route,\n handler: async (context: Parameters<typeof handler>[0]) => {\n try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context, async () => {});\n },\n };\n }\n\n const createHandler = route.createHandler;\n return {\n ...route,\n createHandler: async (args: Parameters<typeof createHandler>[0]) => {\n const handler = await createHandler(args);\n return async (context: Parameters<typeof handler>[0]) => {\n try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context);\n };\n },\n };\n });\n}\n\nexport function factoryRuleBranch(item: FactoryBindingPreparationInput['item']): string {\n const metadata = item.metadata ?? {};\n const issueNumber = metadata.githubIssueNumber ?? metadata.number;\n if (\n item.externalSource?.integrationId === 'github' &&\n item.externalSource.type === 'issue' &&\n typeof issueNumber === 'number'\n ) {\n return `factory/issue-${issueNumber}`;\n }\n const pullRequestNumber = metadata.githubPullRequestNumber ?? metadata.number;\n if (\n item.externalSource?.integrationId === 'github' &&\n item.externalSource.type === 'pull-request' &&\n typeof pullRequestNumber === 'number'\n ) {\n return `factory/pr-${pullRequestNumber}`;\n }\n throw new Error('Factory skill invocation requires a GitHub issue or pull request number.');\n}\n\nasync function prepareFactoryRuleBinding(\n github: GithubIntegration,\n coordinator: FactoryStartCoordinator,\n input: FactoryBindingPreparationInput,\n): Promise<void> {\n const branch = factoryRuleBranch(input.item);\n const repositorySlug =\n typeof input.item.metadata?.repository === 'string' ? input.item.metadata.repository : undefined;\n const preparedSession = await ensureFactoryRuleSession({\n github,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n repositorySlug,\n branch,\n });\n const destinationStage = input.item.stages.length === 1 ? input.item.stages[0] : undefined;\n if (!destinationStage) throw new Error('Factory skill invocation requires one exclusive board stage.');\n\n await coordinator.prepare({\n orgId: input.record.orgId,\n userId: preparedSession.userId,\n factoryProjectId: input.record.factoryProjectId,\n sessionId: preparedSession.sessionId,\n threadTitle: `${input.role === 'review' ? 'PR' : 'Issue'}: ${input.item.title}`,\n kickoffKey: input.record.id,\n destinationStage: destinationStage as 'intake' | 'triage' | 'planning' | 'execute' | 'review' | 'done',\n workItem: {\n id: input.item.id,\n role: input.role,\n input: {\n externalSource: input.item.externalSource,\n parentWorkItemId: input.item.parentWorkItemId,\n title: input.item.title,\n stages: ['intake'],\n sessions: input.item.sessions,\n metadata: input.item.metadata,\n },\n },\n });\n}\n\n/**\n * Build the {@link IntegrationContext} handed to an integration when the\n * factory collects its capabilities (routes, workers). One shape everywhere:\n * `assembleFactoryApiRoutes` uses it per registration, and `MastraFactory` uses it\n * when collecting integration workers at finalize.\n */\nexport function buildIntegrationContext(\n deps: Pick<\n FactoryApiRoutesDeps,\n 'controller' | 'publicOrigin' | 'auth' | 'fleet' | 'factoryStorage' | 'integrationStorage' | 'sourceControlStorage'\n > & {\n stateSigner: StateSigner;\n emitAudit?: AuditEmitter['emit'];\n rules: FactoryRules;\n factoryReady: boolean;\n domains: Pick<FactoryApiRoutesDeps['domains'], 'projects' | 'intake' | 'workItems'>;\n },\n integrationId: string,\n): IntegrationContext {\n return {\n auth: deps.auth,\n fleet: deps.fleet,\n factoryStorage: deps.factoryStorage,\n baseUrl: deps.publicOrigin,\n controller: deps.controller,\n stateSigner: deps.stateSigner,\n storage: {\n generic: deps.integrationStorage.forIntegration(integrationId),\n sourceControl: deps.sourceControlStorage.forIntegration(integrationId),\n projects: deps.domains.projects,\n intake: deps.domains.intake,\n },\n ...(deps.factoryReady ? { rules: { config: deps.rules, workItems: deps.domains.workItems } } : {}),\n ...(deps.emitAudit ? { hooks: { emitAudit: deps.emitAudit } } : {}),\n };\n}\n\n/**\n * Disabled-status stub for the well-known integration ids. The SPA polls\n * `/web/github/status` and `/web/linear/status` unconditionally, so when an\n * integration is absent (or not ready) the status contract must still hold.\n * Unknown custom ids get no stub — the SPA doesn't poll them.\n */\nfunction disabledIntegrationStatusRoutes(deps: FactoryApiRoutesDeps, id: string, configured = false): ApiRoute[] {\n if (id === 'github') {\n return [\n registerApiRoute('/web/github/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n installations: [],\n reason: 'missing_config',\n diagnostics: getGithubFeatureDiagnostics({\n github: undefined,\n auth: deps.auth,\n appDbConfigured: deps.factoryStorage !== undefined,\n stateSigner: deps.stateSigner,\n fleet: deps.fleet,\n }),\n }),\n }),\n ];\n }\n if (id === 'linear') {\n return [\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n workspace: null,\n reason: 'missing_config',\n diagnostics: {\n linearAppConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: true,\n },\n }),\n }),\n ];\n }\n return [];\n}\n\n/**\n * Assemble the custom `/web/*` API routes as Mastra `server.apiRoutes`:\n * - fs browser routes (project picker), confined to `fsRoot`\n * - config routes (provider/API-key/model-pack/OM management)\n * - every registered integration's `routes()` surface (full set when ready,\n * disabled-status stub otherwise), plus stubs for absent known ids\n */\nexport function assembleFactoryApiRoutes(deps: FactoryApiRoutesDeps): ApiRoute[] {\n const emitAudit: AuditEmitter['emit'] = args => deps.audit.emit(args);\n const registrations = deps.integrations ?? [];\n const githubRegistration = registrations.find(({ integration }) => integration.id === 'github');\n const githubStorage = githubRegistration ? deps.sourceControlStorage.forIntegration('github') : undefined;\n const githubIntegration = githubRegistration?.integration as GithubIntegration | undefined;\n\n const integrationRoutes = registrations.flatMap(registration => {\n const { integration } = registration;\n if (!deps.stateSigner) return disabledIntegrationStatusRoutes(deps, integration.id, true);\n const context = buildIntegrationContext({ ...deps, stateSigner: deps.stateSigner, emitAudit }, integration.id);\n return guardIntegrationRoutes({ ...registration, routes: integration.routes(context) });\n });\n // Absent known integrations still get their disabled-status stub.\n const absentStubs = ['github', 'linear']\n .filter(id => !registrations.some(({ integration }) => integration.id === id))\n .flatMap(id => disabledIntegrationStatusRoutes(deps, id));\n\n const transitionService = deps.factoryReady\n ? (deps.factoryTransitionService ??\n new FactoryTransitionService({ rules: deps.rules, storage: deps.domains.workItems }))\n : undefined;\n const startCoordinator = transitionService\n ? new FactoryStartCoordinator(\n deps.controller,\n deps.domains.workItems,\n transitionService,\n githubIntegration?.sourceControlStorage,\n deps.domains.memorySettings,\n )\n : undefined;\n if (transitionService && startCoordinator) {\n deps.onFactoryRuntime?.({\n transitionService,\n ...(githubIntegration\n ? {\n prepareBinding: (input: FactoryBindingPreparationInput) =>\n prepareFactoryRuleBinding(githubIntegration, startCoordinator, input),\n }\n : {}),\n });\n }\n\n return [\n ...buildFsRoutes({\n root: deps.fsRoot,\n sessionFs: {\n auth: deps.auth,\n fleet: deps.fleet,\n sessions: deps.sourceControlStorage.forIntegration('github').sessions,\n },\n }),\n ...new ConfigRoutes({\n auth: deps.auth,\n controller: deps.controller,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n modelPacks: deps.domains.modelPacks,\n memorySettings: deps.domains.memorySettings,\n customProviders: deps.domains.customProviders,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n onCustomProvidersChanged: invalidateCustomProvidersSnapshots,\n }).routes(),\n ...new OAuthRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n }).routes(),\n ...new SkillRoutes({\n auth: deps.auth,\n controllerId: deps.controllerId,\n controller: deps.controller,\n sourceControlStorage: githubStorage,\n ensureSourceControlReady: githubRegistration?.ensureReady,\n }).routes(),\n ...integrationRoutes,\n ...absentStubs,\n ...(deps.intakeReady\n ? new IntakeRoutes({\n auth: deps.auth,\n audit: deps.audit,\n intake: deps.domains.intake,\n integrations: (deps.integrations ?? []).flatMap(({ integration }) =>\n integration.intake ? [{ id: integration.id, intake: integration.intake }] : [],\n ),\n }).routes()\n : []),\n ...(deps.factoryReady\n ? new WorkItemRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n queueHealth: deps.domains.queueHealth,\n transitionService,\n startCoordinator,\n }).routes()\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;AAmFA,SAAS,uBAAuB,EAC9B,aACA,OACA,aACA,UAC+D;CAC/D,IAAI,OAAO,OAAO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IAAI,aAAa;GACf,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,QAAQ,KAAK,QAAQ;GACrB,eAAe,KAAK,gBAAgB,CAAC,EAAA,CAAG,SAAS,EAAE,kBACjD,YAAY,SAAS,CAAC;IAAE,IAAI,YAAY;IAAI,QAAQ,YAAY;GAAO,CAAC,IAAI,CAAC,CAC/E;EACF,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;EACL,GAAI,KAAK,eACL,IAAI,eAAe;GACjB,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,aAAa,KAAK,QAAQ;GAC1B;GACA;EACF,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;CACP;AACF"}
1
+ {"version":3,"file":"surface.js","names":[],"sources":["../../src/routes/surface.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { FactoryStorage } from '@mastra/core/storage';\n\nimport type { FactoryIntegration, IntegrationContext } from '../integrations/base.js';\nimport { getGithubFeatureDiagnostics } from '../integrations/github/config.js';\nimport { ensureFactoryRuleSession } from '../integrations/github/factory-session.js';\nimport type { GithubIntegration } from '../integrations/github/integration.js';\nimport type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';\nimport { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { FactoryTransitionService } from '../rules/transition-service.js';\nimport type { FactoryRules } from '../rules/types.js';\nimport type { SandboxFleet } from '../sandbox/fleet.js';\nimport type { StateSigner } from '../state-signing.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport type { ChannelIdentityStorage } from '../storage/domains/channel-identity/base.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { IntegrationStorage } from '../storage/domains/integrations/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { ModelPacksStorage } from '../storage/domains/model-packs/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport type { SourceControlStorage } from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { ConfigRoutes } from './config.js';\nimport { invalidateCustomProvidersSnapshots } from './custom-provider-source.js';\nimport { buildFsRoutes } from './fs.js';\nimport { IntakeRoutes } from './intake.js';\nimport { OAuthRoutes } from './oauth.js';\nimport type { RouteAuth } from './route.js';\nimport { SkillRoutes } from './skills.js';\nimport { invalidateTenantCredentialSnapshots } from './tenant-credentials.js';\nimport { WorkItemRoutes } from './work-items.js';\n\nexport interface IntegrationRegistration {\n integration: FactoryIntegration;\n ready: boolean;\n ensureReady: () => Promise<void>;\n}\n\nexport interface FactoryApiRoutesDeps {\n controllerId: string;\n controller: AgentController<MastraCodeState>;\n /** Request-auth seam threaded from the host (no service locator). */\n auth: RouteAuth;\n authStorage: AuthStorage;\n audit: AuditEmitter;\n fsRoot?: string;\n publicOrigin: string;\n stateSigner?: StateSigner;\n /** Sandbox fleet constructed by the factory (disabled when no machine). */\n fleet: SandboxFleet;\n /** Root factory storage backend (distributed locks, app-db diagnostics). */\n factoryStorage?: FactoryStorage;\n integrationStorage: IntegrationStorage;\n sourceControlStorage: SourceControlStorage;\n /** App-table domain handles, registered and owned by `MastraFactory.prepare()`. */\n domains: {\n intake: IntakeStorage;\n modelCredentials: ModelCredentialsStorage;\n memorySettings: MemorySettingsStorage;\n customProviders: CustomProvidersStorage;\n modelPacks: ModelPacksStorage;\n projects: FactoryProjectsStorage;\n queueHealth: QueueHealthStorage;\n workItems: WorkItemsStorage;\n channelIdentity: ChannelIdentityStorage;\n };\n integrations?: IntegrationRegistration[];\n intakeReady: boolean;\n factoryReady: boolean;\n /** Resolved Factory rule set, threaded from the host (no service locator). */\n rules: FactoryRules;\n factoryTransitionService?: FactoryTransitionService;\n onFactoryRuntime?: (runtime: {\n transitionService: FactoryTransitionService;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n }) => void;\n}\n\nfunction guardIntegrationRoutes({\n integration,\n ready,\n ensureReady,\n routes,\n}: IntegrationRegistration & { routes: ApiRoute[] }): ApiRoute[] {\n if (ready) return routes;\n return routes.map(route => {\n if ('handler' in route) {\n const handler = route.handler;\n return {\n ...route,\n handler: async (context: Parameters<typeof handler>[0]) => {\n try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context, async () => {});\n },\n };\n }\n\n const createHandler = route.createHandler;\n return {\n ...route,\n createHandler: async (args: Parameters<typeof createHandler>[0]) => {\n const handler = await createHandler(args);\n return async (context: Parameters<typeof handler>[0]) => {\n try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context);\n };\n },\n };\n });\n}\n\nexport function factoryRuleBranch(item: FactoryBindingPreparationInput['item']): string {\n const metadata = item.metadata ?? {};\n const issueNumber = metadata.githubIssueNumber ?? metadata.number;\n if (\n item.externalSource?.integrationId === 'github' &&\n item.externalSource.type === 'issue' &&\n typeof issueNumber === 'number'\n ) {\n return `factory/issue-${issueNumber}`;\n }\n const pullRequestNumber = metadata.githubPullRequestNumber ?? metadata.number;\n if (\n item.externalSource?.integrationId === 'github' &&\n item.externalSource.type === 'pull-request' &&\n typeof pullRequestNumber === 'number'\n ) {\n return `factory/pr-${pullRequestNumber}`;\n }\n throw new Error('Factory skill invocation requires a GitHub issue or pull request number.');\n}\n\nasync function prepareFactoryRuleBinding(\n github: GithubIntegration,\n coordinator: FactoryStartCoordinator,\n input: FactoryBindingPreparationInput,\n): Promise<void> {\n const branch = factoryRuleBranch(input.item);\n const repositorySlug =\n typeof input.item.metadata?.repository === 'string' ? input.item.metadata.repository : undefined;\n const preparedSession = await ensureFactoryRuleSession({\n github,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n repositorySlug,\n branch,\n });\n const destinationStage = input.item.stages.length === 1 ? input.item.stages[0] : undefined;\n if (!destinationStage) throw new Error('Factory skill invocation requires one exclusive board stage.');\n\n await coordinator.prepare({\n orgId: input.record.orgId,\n userId: preparedSession.userId,\n factoryProjectId: input.record.factoryProjectId,\n sessionId: preparedSession.sessionId,\n threadTitle: `${input.role === 'review' ? 'PR' : 'Issue'}: ${input.item.title}`,\n kickoffKey: input.record.id,\n destinationStage: destinationStage as 'intake' | 'triage' | 'planning' | 'execute' | 'review' | 'done',\n workItem: {\n id: input.item.id,\n role: input.role,\n input: {\n externalSource: input.item.externalSource,\n parentWorkItemId: input.item.parentWorkItemId,\n title: input.item.title,\n stages: ['intake'],\n sessions: input.item.sessions,\n metadata: input.item.metadata,\n },\n },\n });\n}\n\n/**\n * Build the {@link IntegrationContext} handed to an integration when the\n * factory collects its capabilities (routes, workers). One shape everywhere:\n * `assembleFactoryApiRoutes` uses it per registration, and `MastraFactory` uses it\n * when collecting integration workers at finalize.\n */\nexport function buildIntegrationContext(\n deps: Pick<\n FactoryApiRoutesDeps,\n 'controller' | 'publicOrigin' | 'auth' | 'fleet' | 'factoryStorage' | 'integrationStorage' | 'sourceControlStorage'\n > & {\n stateSigner: StateSigner;\n emitAudit?: AuditEmitter['emit'];\n rules: FactoryRules;\n factoryReady: boolean;\n domains: Pick<FactoryApiRoutesDeps['domains'], 'projects' | 'intake' | 'workItems' | 'channelIdentity'>;\n },\n integrationId: string,\n): IntegrationContext {\n return {\n auth: deps.auth,\n fleet: deps.fleet,\n factoryStorage: deps.factoryStorage,\n baseUrl: deps.publicOrigin,\n controller: deps.controller,\n stateSigner: deps.stateSigner,\n storage: {\n generic: deps.integrationStorage.forIntegration(integrationId),\n sourceControl: deps.sourceControlStorage.forIntegration(integrationId),\n projects: deps.domains.projects,\n intake: deps.domains.intake,\n channelIdentity: deps.domains.channelIdentity,\n },\n ...(deps.factoryReady ? { rules: { config: deps.rules, workItems: deps.domains.workItems } } : {}),\n ...(deps.emitAudit ? { hooks: { emitAudit: deps.emitAudit } } : {}),\n };\n}\n\n/**\n * Disabled-status stub for the well-known integration ids. The SPA polls\n * `/web/github/status` and `/web/linear/status` unconditionally, so when an\n * integration is absent (or not ready) the status contract must still hold.\n * Unknown custom ids get no stub — the SPA doesn't poll them.\n */\nfunction disabledIntegrationStatusRoutes(deps: FactoryApiRoutesDeps, id: string, configured = false): ApiRoute[] {\n if (id === 'github') {\n return [\n registerApiRoute('/web/github/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n installations: [],\n reason: 'missing_config',\n diagnostics: getGithubFeatureDiagnostics({\n github: undefined,\n auth: deps.auth,\n appDbConfigured: deps.factoryStorage !== undefined,\n stateSigner: deps.stateSigner,\n fleet: deps.fleet,\n }),\n }),\n }),\n ];\n }\n if (id === 'linear') {\n return [\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n workspace: null,\n reason: 'missing_config',\n diagnostics: {\n linearAppConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: true,\n },\n }),\n }),\n ];\n }\n return [];\n}\n\n/**\n * Assemble the custom `/web/*` API routes as Mastra `server.apiRoutes`:\n * - fs browser routes (project picker), confined to `fsRoot`\n * - config routes (provider/API-key/model-pack/OM management)\n * - every registered integration's `routes()` surface (full set when ready,\n * disabled-status stub otherwise), plus stubs for absent known ids\n */\nexport function assembleFactoryApiRoutes(deps: FactoryApiRoutesDeps): ApiRoute[] {\n const emitAudit: AuditEmitter['emit'] = args => deps.audit.emit(args);\n const registrations = deps.integrations ?? [];\n const githubRegistration = registrations.find(({ integration }) => integration.id === 'github');\n const githubStorage = githubRegistration ? deps.sourceControlStorage.forIntegration('github') : undefined;\n const githubIntegration = githubRegistration?.integration as GithubIntegration | undefined;\n\n const integrationRoutes = registrations.flatMap(registration => {\n const { integration } = registration;\n if (!deps.stateSigner) return disabledIntegrationStatusRoutes(deps, integration.id, true);\n const context = buildIntegrationContext({ ...deps, stateSigner: deps.stateSigner, emitAudit }, integration.id);\n return guardIntegrationRoutes({ ...registration, routes: integration.routes(context) });\n });\n // Absent known integrations still get their disabled-status stub.\n const absentStubs = ['github', 'linear']\n .filter(id => !registrations.some(({ integration }) => integration.id === id))\n .flatMap(id => disabledIntegrationStatusRoutes(deps, id));\n\n const transitionService = deps.factoryReady\n ? (deps.factoryTransitionService ??\n new FactoryTransitionService({ rules: deps.rules, storage: deps.domains.workItems }))\n : undefined;\n const startCoordinator = transitionService\n ? new FactoryStartCoordinator(\n deps.controller,\n deps.domains.workItems,\n transitionService,\n githubIntegration?.sourceControlStorage,\n deps.domains.memorySettings,\n )\n : undefined;\n if (transitionService && startCoordinator) {\n deps.onFactoryRuntime?.({\n transitionService,\n ...(githubIntegration\n ? {\n prepareBinding: (input: FactoryBindingPreparationInput) =>\n prepareFactoryRuleBinding(githubIntegration, startCoordinator, input),\n }\n : {}),\n });\n }\n\n return [\n ...buildFsRoutes({\n root: deps.fsRoot,\n sessionFs: {\n auth: deps.auth,\n fleet: deps.fleet,\n sessions: deps.sourceControlStorage.forIntegration('github').sessions,\n },\n }),\n ...new ConfigRoutes({\n auth: deps.auth,\n controller: deps.controller,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n modelPacks: deps.domains.modelPacks,\n memorySettings: deps.domains.memorySettings,\n customProviders: deps.domains.customProviders,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n onCustomProvidersChanged: invalidateCustomProvidersSnapshots,\n }).routes(),\n ...new OAuthRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n }).routes(),\n ...new SkillRoutes({\n auth: deps.auth,\n controllerId: deps.controllerId,\n controller: deps.controller,\n sourceControlStorage: githubStorage,\n ensureSourceControlReady: githubRegistration?.ensureReady,\n }).routes(),\n ...integrationRoutes,\n ...absentStubs,\n ...(deps.intakeReady\n ? new IntakeRoutes({\n auth: deps.auth,\n audit: deps.audit,\n intake: deps.domains.intake,\n integrations: (deps.integrations ?? []).flatMap(({ integration }) =>\n integration.intake ? [{ id: integration.id, intake: integration.intake }] : [],\n ),\n }).routes()\n : []),\n ...(deps.factoryReady\n ? new WorkItemRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n queueHealth: deps.domains.queueHealth,\n transitionService,\n startCoordinator,\n }).routes()\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;AAqFA,SAAS,uBAAuB,EAC9B,aACA,OACA,aACA,UAC+D;CAC/D,IAAI,OAAO,OAAO;CAClB,OAAO,OAAO,KAAI,UAAS;EACzB,IAAI,aAAa,OAAO;GACtB,MAAM,UAAU,MAAM;GACtB,OAAO;IACL,GAAG;IACH,SAAS,OAAO,YAA2C;KACzD,IAAI;MACF,MAAM,YAAY;KACpB,QAAQ;MACN,OAAO,QAAQ,KACb;OAAE,OAAO;OAA2B,SAAS,GAAG,YAAY,GAAG;MAA8B,GAC7F,GACF;KACF;KACA,OAAO,QAAQ,SAAS,YAAY,CAAC,CAAC;IACxC;GACF;EACF;EAEA,MAAM,gBAAgB,MAAM;EAC5B,OAAO;GACL,GAAG;GACH,eAAe,OAAO,SAA8C;IAClE,MAAM,UAAU,MAAM,cAAc,IAAI;IACxC,OAAO,OAAO,YAA2C;KACvD,IAAI;MACF,MAAM,YAAY;KACpB,QAAQ;MACN,OAAO,QAAQ,KACb;OAAE,OAAO;OAA2B,SAAS,GAAG,YAAY,GAAG;MAA8B,GAC7F,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  }) => Promise<void>;
22
+ maxInFlight?: number;
22
23
  }
23
24
  export declare class FactoryDecisionDispatcher {
24
25
  #private;
@@ -34,6 +35,7 @@ export declare const FACTORY_DISPATCH_CONSTANTS: {
34
35
  readonly maxAttempts: 5;
35
36
  readonly maxErrorLength: 512;
36
37
  readonly maxBackoffMs: 60000;
38
+ readonly maxInFlight: 25;
37
39
  readonly stages: readonly ["intake", "triage", "planning", "execute", "review", "done", "canceled"];
38
40
  };
39
41
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"dispatcher.d.ts","sourceRoot":"","sources":["../../src/rules/dispatcher.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAKrE,OAAO,KAAK,EACV,6BAA6B,EAG7B,WAAW,EACX,gBAAgB,EACjB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAuBxE,KAAK,iBAAiB,GAAG,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,EAAE,sBAAsB,CAAC,CAAC;AAExF,MAAM,WAAW,8BAA8B;IAC7C,MAAM,EAAE,6BAA6B,CAAC;IACtC,IAAI,EAAE,WAAW,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,gCAAgC;IAC/C,UAAU,EAAE,iBAAiB,CAAC;IAC9B,iBAAiB,EAAE,IAAI,CAAC,wBAAwB,EAAE,YAAY,CAAC,CAAC;IAChE,OAAO,EAAE,gBAAgB,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,oBAAoB,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,8BAA8B,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1E,gBAAgB,CA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