@mastra/factory 0.5.0 → 0.6.0-alpha.1
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.
- package/CHANGELOG.md +42 -0
- package/dist/auth.d.ts +2 -0
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +2 -0
- package/dist/auth.js.map +1 -1
- package/dist/capabilities/intake.d.ts +1 -0
- package/dist/capabilities/intake.d.ts.map +1 -1
- package/dist/capabilities/version-control.d.ts +2 -0
- package/dist/capabilities/version-control.d.ts.map +1 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +2 -1
- package/dist/factory.js.map +1 -1
- package/dist/integrations/base.d.ts +6 -0
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/github/integration.d.ts +1 -0
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +11 -1
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +20 -46
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +4 -0
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +68 -10
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox-release.d.ts +16 -1
- package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
- package/dist/integrations/github/sandbox-release.js +42 -1
- package/dist/integrations/github/sandbox-release.js.map +1 -1
- package/dist/integrations/linear/integration.d.ts +2 -0
- package/dist/integrations/linear/integration.d.ts.map +1 -1
- package/dist/integrations/linear/integration.js +5 -1
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +1 -0
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/linear/rules.d.ts +2 -0
- package/dist/integrations/linear/rules.d.ts.map +1 -1
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +7 -0
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/slack/integration.d.ts.map +1 -1
- package/dist/integrations/slack/integration.js +3 -2
- package/dist/integrations/slack/integration.js.map +1 -1
- package/dist/integrations/slack/slack.d.ts +37 -110
- package/dist/integrations/slack/slack.d.ts.map +1 -1
- package/dist/integrations/slack/slack.js +49 -44
- package/dist/integrations/slack/slack.js.map +1 -1
- package/dist/routes/surface.d.ts +11 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +18 -8
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/defaults.d.ts.map +1 -1
- package/dist/rules/defaults.js +35 -4
- package/dist/rules/defaults.js.map +1 -1
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +7 -26
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/types.d.ts +10 -0
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/session/factory-session.d.ts +116 -0
- package/dist/session/factory-session.d.ts.map +1 -0
- package/dist/session/factory-session.js +162 -0
- package/dist/session/factory-session.js.map +1 -0
- package/dist/storage/domains/audit/domain.d.ts +9 -2
- package/dist/storage/domains/audit/domain.d.ts.map +1 -1
- package/dist/storage/domains/audit/domain.js +106 -4
- package/dist/storage/domains/audit/domain.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +11 -0
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/package.json +7 -7
- package/dist/integrations/github/factory-session.d.ts +0 -12
- package/dist/integrations/github/factory-session.d.ts.map +0 -1
- package/dist/integrations/github/factory-session.js +0 -37
- package/dist/integrations/github/factory-session.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.js","names":["#resolveIntakeDispatch","#listIntakeIssues","#getIntakeIssue","#createIntakeComment","#updateIntakeIssue","#sourceControlStorage","#listPullRequests","#getPullRequest","#createPullRequest","#updatePullRequest","#closePullRequest","#mergePullRequest","#listComments","#createComment","#updateComment","#deleteComment","#listReviews","#getReview","#createReview","#updateReview","#submitReview","#dismissReview","#deletePendingReview","#listReviewComments","#createReviewComment","#updateReviewComment","#deleteReviewComment","#listRequestedReviewers","#requestReviewers","#removeReviewers","#appId","#privateKey","#clientId","#clientSecret","#slug","#webhookSecret","#storage","#appAuth","#repositoryClient"],"sources":["../../../src/integrations/github/integration.ts"],"sourcesContent":["/**\n * `GithubIntegration` — the injectable GitHub App integration for the web\n * factory.\n *\n * The deploy entry (`src/mastra/index.ts`) reads the `GITHUB_APP_*` env vars\n * once, constructs an instance, and passes it to `MastraFactory` (the same\n * dependency-injection pattern as the auth adapter and the sandbox machine).\n * The factory seeds it into the runtime-config registry for the feature gate\n * (`./config.ts`) and hands the instance to every consumer explicitly — route\n * handlers receive it through `routes()`, the webhook fan-out and session\n * subscription tools through their deps.\n *\n * The class owns:\n * - the GitHub App credentials (validated + PEM-normalized at construction),\n * - every GitHub API operation the web surface performs (Octokit factories,\n * token minting, installation/repo/issue/PR listings, OAuth exchange),\n * - the webhook secret used to verify GitHub webhook deliveries,\n * - its own HTTP surface: `routes()` returns the `/web/github/*` +\n * `/auth/github/*` Mastra `apiRoutes`.\n *\n * A custom integration (different app per tenant, custom Octokit config) can\n * subclass this and override individual methods — everything downstream only\n * talks to the instance.\n */\n\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\nimport { createAppAuth } from '@octokit/auth-app';\nimport { Octokit } from '@octokit/rest';\n\nimport type { IntegrationConnection } from '../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n ListIntakeIssuesInput,\n UpdateIntakeIssueInput,\n} from '../../capabilities/intake.js';\nimport type {\n PullRequest,\n PullRequestComment,\n Review,\n ReviewComment,\n VersionControl,\n} from '../../capabilities/version-control.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { runGithubIssueTriage } from './issue-triage.js';\nimport { GithubReconcileWorker } from './reconcile-worker.js';\nimport { buildGithubRoutes } from './routes.js';\nimport { attachGithubReconciler, attachGithubRules } from './rules.js';\nimport type { ReconcilePullRequestState } from './rules.js';\nimport {\n createGithubSubscriptionTools,\n parseCreatedPullRequest,\n subscribeCurrentSessionToPullRequest,\n} from './session-subscriptions.js';\nimport type { GithubSubscriptionStorage } from './subscriptions.js';\n\ntype InputOf<TMethod extends keyof VersionControl> = VersionControl[TMethod] extends (input: infer TInput) => unknown\n ? TInput\n : never;\n\n/**\n * Normalize a PEM private key supplied via env. Env tooling tends to mangle\n * multi-line PEMs, so two single-line forms are supported:\n * - `\\n`-escaped: literal `\\n` sequences become real newlines\n * - fully flattened: newlines stripped entirely — the PEM is rebuilt by\n * re-wrapping the base64 body (Node's decoder rejects header/body/footer\n * on one line with `error:1E08010C:DECODER routines::unsupported`)\n */\nexport function normalizePrivateKey(raw: string): string {\n const key = raw.replace(/\\\\n/g, '\\n');\n if (key.includes('\\n')) return key;\n const flattened = key.trim().match(/^(-----BEGIN [A-Z0-9 ]+-----)\\s*(.+?)\\s*(-----END [A-Z0-9 ]+-----)$/);\n if (!flattened) return key;\n const body = flattened[2]!.replace(/\\s+/g, '');\n return `${flattened[1]}\\n${body.match(/.{1,64}/g)!.join('\\n')}\\n${flattened[3]}\\n`;\n}\n\nexport interface UserInstallation {\n installationId: number;\n accountLogin: string | null;\n accountType: string | null;\n}\n\nexport interface RepoSummary {\n id: number;\n fullName: string;\n name: string;\n owner: string;\n defaultBranch: string;\n private: boolean;\n installationId: number;\n}\n\nexport type GithubRepositoryPermission = 'admin' | 'maintain' | 'write' | 'triage' | 'read' | 'none';\n\nexport interface IssueSummary {\n number: number;\n title: string;\n url: string;\n author: string | null;\n labels: string[];\n comments: number;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Page size for issue/PR listings; one GitHub API call per page. */\nexport const LIST_PAGE_SIZE = 30;\n\nexport interface IssuePage {\n issues: IssueSummary[];\n /** Next page number to request, or `null` when this was the last page. */\n nextPage: number | null;\n}\n\nexport interface ListRepoOpenIssuesOptions {\n label?: string;\n}\n\nexport interface GithubIntegrationConfig {\n /** GitHub App id (the numeric id, as a string). */\n appId: string;\n /**\n * App private key (PEM). Multi-line, `\\n`-escaped, and fully flattened\n * single-line forms are all accepted (normalized at construction).\n */\n privateKey: string;\n /** OAuth client id of the GitHub App. */\n clientId: string;\n /** OAuth client secret of the GitHub App. */\n clientSecret: string;\n /** App slug — the URL name used to build the install URL. */\n slug: string;\n /**\n * Secret GitHub uses to sign webhook deliveries. Omitted → webhook\n * signature verification rejects all deliveries. Also serves as the default\n * replica-stable OAuth/install `state` secret (see `./config.ts`).\n */\n webhookSecret?: string;\n}\n\n/** Human-readable names of the required config fields, for construction errors. */\nconst REQUIRED_FIELDS = ['appId', 'privateKey', 'clientId', 'clientSecret', 'slug'] as const;\n\nexport class GithubIntegration implements FactoryIntegration {\n /** Stable integration identifier (see `../factory-integration.ts`). */\n readonly id = 'github';\n readonly intake: Intake = {\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: async ({ orgId }) => {\n const installations = await this.sourceControlStorage.installations.list({ orgId });\n const repositories = await Promise.all(\n installations.map(installation =>\n this.sourceControlStorage.repositories.list({ orgId, installationId: installation.id }),\n ),\n );\n return repositories.flat().map(repository => ({\n id: repository.id,\n name: repository.slug,\n type: 'repository',\n metadata: { defaultBranch: repository.defaultBranch },\n }));\n },\n listItems: async ({ orgId, sourceIds, cursor }) => {\n const page = cursor ? Number.parseInt(cursor, 10) : 1;\n const requestedPage = Number.isSafeInteger(page) && page > 0 ? page : 1;\n const pages = await Promise.all(\n sourceIds.map(async sourceId => {\n const repository = await this.sourceControlStorage.repositories.get({ orgId, id: sourceId });\n if (!repository) return { items: [], hasNextPage: false };\n const installation = await this.sourceControlStorage.installations.get({\n orgId,\n id: repository.installationId,\n });\n if (!installation) return { items: [], hasNextPage: false };\n const installationId = Number.parseInt(installation.externalId, 10);\n if (!Number.isSafeInteger(installationId)) return { items: [], hasNextPage: false };\n const [issues, pullRequests] = await Promise.all([\n this.listRepoOpenIssues(installationId, repository.slug, requestedPage),\n this.versionControl.listPullRequests({\n connection: { type: 'app-installation', installationId },\n sourceId: repository.slug,\n includeDrafts: false,\n cursor: String(requestedPage),\n }),\n ]);\n return {\n items: [\n ...issues.issues.map(issue => ({\n source: { type: 'issue', externalId: `${repository.externalId}:${issue.number}`, url: issue.url },\n sourceId: repository.id,\n title: issue.title,\n status: 'open',\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n metadata: { repository: repository.slug, number: issue.number, author: issue.author },\n })),\n ...pullRequests.pullRequests.map(pullRequest => ({\n source: {\n type: 'pull-request',\n externalId: `${repository.externalId}:${pullRequest.id}`,\n url: pullRequest.url,\n },\n sourceId: repository.id,\n title: pullRequest.title,\n status: 'open',\n createdAt: pullRequest.createdAt,\n updatedAt: pullRequest.updatedAt,\n metadata: {\n repository: repository.slug,\n number: Number(pullRequest.id),\n author: pullRequest.author,\n baseBranch: pullRequest.baseBranch,\n headBranch: pullRequest.headBranch,\n },\n })),\n ],\n hasNextPage: issues.nextPage !== null || pullRequests.nextCursor !== null,\n };\n }),\n );\n return {\n items: pages.flatMap(result => result.items),\n nextCursor: pages.some(result => result.hasNextPage) ? String(requestedPage + 1) : null,\n };\n },\n listIssues: input => this.#listIntakeIssues(input),\n getIssue: input => this.#getIntakeIssue(input),\n createComment: input => this.#createIntakeComment(input),\n updateIssue: input => this.#updateIntakeIssue(input),\n };\n readonly versionControl: VersionControl = {\n initialize: ({ storage }) => {\n this.#sourceControlStorage = storage;\n },\n registerInstallation: ({ orgId, userId, installation }) =>\n this.sourceControlStorage.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.sourceControlStorage.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 const repository = await this.sourceControlStorage.repositories.get({ orgId, id: repositoryId });\n if (!repository) throw new Error('Version-control repository not found.');\n const installation = await this.sourceControlStorage.installations.get({\n orgId,\n id: repository.installationId,\n });\n if (!installation) throw new Error('Version-control installation not found.');\n const installationId = Number.parseInt(installation.externalId, 10);\n if (!Number.isSafeInteger(installationId)) throw new Error('GitHub installation id is invalid.');\n return {\n cloneUrl: `https://github.com/${repository.slug}.git`,\n authorization: { scheme: 'bearer', token: await this.mintInstallationToken(installationId) },\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.#closePullRequest(input),\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.#listRequestedReviewers(input),\n requestReviewers: input => this.#requestReviewers(input),\n removeRequestedReviewers: input => this.#removeReviewers(input),\n };\n /**\n * The OAuth/install flow round-trips a signed `state` through GitHub, so a\n * multi-replica deploy needs a deployment-stable state secret.\n */\n readonly requiresStableStateSigner = true;\n\n readonly #appId: string;\n readonly #privateKey: string;\n readonly #clientId: string;\n readonly #clientSecret: string;\n readonly #slug: string;\n readonly #webhookSecret: string | undefined;\n #storage: IntegrationContext['storage'] | undefined;\n #sourceControlStorage: IntegrationContext['storage']['sourceControl'] | undefined;\n\n constructor(config: GithubIntegrationConfig) {\n const missing = REQUIRED_FIELDS.filter(field => !config[field]);\n if (missing.length > 0) {\n throw new Error(\n `GithubIntegration: missing required config field(s): ${missing.join(', ')}. ` +\n `Provide the full GitHub App credentials (appId, privateKey, clientId, clientSecret, slug) ` +\n `or omit the integration to disable GitHub-backed repositories.`,\n );\n }\n this.#appId = config.appId;\n this.#privateKey = normalizePrivateKey(config.privateKey);\n this.#clientId = config.clientId;\n this.#clientSecret = config.clientSecret;\n this.#slug = config.slug;\n this.#webhookSecret = config.webhookSecret || undefined;\n }\n\n /** App slug — the URL name used to build the install URL. */\n get slug(): string {\n return this.#slug;\n }\n\n get genericStorage(): IntegrationContext['storage']['generic'] {\n if (!this.#storage) throw new Error('GithubIntegration storage has not been initialized.');\n return this.#storage.generic;\n }\n\n get sourceControlStorage(): IntegrationContext['storage']['sourceControl'] {\n const storage = this.#sourceControlStorage ?? this.#storage?.sourceControl;\n if (!storage) throw new Error('GithubIntegration source-control storage has not been initialized.');\n return storage;\n }\n\n get integrationStorage(): GithubSubscriptionStorage {\n if (!this.#storage) throw new Error('GithubIntegration storage has not been initialized.');\n return this.#storage.generic as unknown as GithubSubscriptionStorage;\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 = await this.sourceControlStorage.repositories.findByExternalId({\n orgId,\n externalId: target.repositoryId,\n });\n if (!repository) return null;\n const installation = await this.sourceControlStorage.installations.get({ orgId, id: repository.installationId });\n if (!installation) return null;\n const installationId = Number.parseInt(installation.externalId, 10);\n if (!Number.isSafeInteger(installationId)) return null;\n return {\n connection: { type: 'app-installation', installationId },\n sourceId: repository.slug,\n issueId: target.issueId,\n };\n }\n\n /** Secret GitHub uses to sign webhook deliveries, when configured. */\n get webhookSecret(): string | undefined {\n return this.#webhookSecret;\n }\n\n #appAuth() {\n return {\n appId: this.#appId,\n privateKey: this.#privateKey,\n clientId: this.#clientId,\n clientSecret: this.#clientSecret,\n };\n }\n\n /**\n * Octokit authenticated as the GitHub App itself (app JWT). Used for\n * app-level operations and to mint installation tokens.\n */\n getAppOctokit(): Octokit {\n return new Octokit({ authStrategy: createAppAuth, auth: this.#appAuth() });\n }\n\n /**\n * Octokit authenticated as a specific installation (installation access\n * token). Used to list repos and to operate on a repo on the user's behalf.\n */\n getInstallationOctokit(installationId: number): Octokit {\n return new Octokit({ authStrategy: createAppAuth, auth: { ...this.#appAuth(), installationId } });\n }\n\n /** Octokit authenticated as a user via their OAuth token (the identify step). */\n getUserOctokit(userToken: string): Octokit {\n return new Octokit({ auth: userToken });\n }\n\n /**\n * Mint a short-lived installation access token. Returned token is used only\n * server-side / inside the sandbox clone URL and never sent to the browser.\n */\n async mintInstallationToken(installationId: number): Promise<string> {\n const auth = createAppAuth(this.#appAuth());\n const installationAuth = await auth({ type: 'installation', installationId });\n return installationAuth.token;\n }\n\n /**\n * List the installations the authenticated user can access, via their OAuth\n * token (`GET /user/installations`).\n */\n async listUserInstallations(userToken: string): Promise<UserInstallation[]> {\n const octokit = this.getUserOctokit(userToken);\n const installations = await octokit.paginate(octokit.apps.listInstallationsForAuthenticatedUser, {\n per_page: 100,\n });\n return installations.map(inst => ({\n installationId: inst.id,\n accountLogin: inst.account && 'login' in inst.account ? inst.account.login : null,\n accountType: inst.account && 'type' in inst.account ? inst.account.type : null,\n }));\n }\n\n /** List repos accessible to an installation (paginated). */\n async listInstallationRepos(installationId: number): Promise<RepoSummary[]> {\n const octokit = this.getInstallationOctokit(installationId);\n const repos = await octokit.paginate(octokit.apps.listReposAccessibleToInstallation, {\n per_page: 100,\n });\n return repos.map(repo => ({\n id: repo.id,\n fullName: repo.full_name,\n name: repo.name,\n owner: repo.owner.login,\n defaultBranch: repo.default_branch,\n private: repo.private,\n installationId,\n }));\n }\n\n /**\n * The authenticated user's permission level on a repo, through the\n * installation. `undefined` when the repo/user is not accessible.\n */\n async getRepositoryCollaboratorPermission(\n installationId: number,\n repoFullName: string,\n username: string,\n signal?: AbortSignal,\n ): Promise<GithubRepositoryPermission | undefined> {\n const parts = splitRepoFullName(repoFullName);\n if (!parts) return undefined;\n try {\n const { data } = await this.getInstallationOctokit(installationId).repos.getCollaboratorPermissionLevel({\n ...parts,\n username,\n request: { signal },\n });\n return data.permission as GithubRepositoryPermission;\n } catch {\n return undefined;\n }\n }\n\n /**\n * Fetch a single repo's metadata through an installation token and confirm\n * the installation actually has access to it. Returns `null` when the repo\n * is not accessible to the installation (so a client can't create a project\n * for an arbitrary repo under an installation id it merely owns).\n */\n async getInstallationRepo(installationId: number, repoFullName: string): Promise<RepoSummary | null> {\n const parts = splitRepoFullName(repoFullName);\n if (!parts) return null;\n const octokit = this.getInstallationOctokit(installationId);\n try {\n const { data } = await octokit.repos.get(parts);\n return {\n id: data.id,\n fullName: data.full_name,\n name: data.name,\n owner: data.owner.login,\n defaultBranch: data.default_branch,\n private: data.private,\n installationId,\n };\n } catch {\n return null;\n }\n }\n\n async #listIntakeIssues(input: ListIntakeIssuesInput): Promise<{ issues: IntakeIssue[]; nextCursor: string | null }> {\n const installationId = getGithubInstallationId(input.connection);\n const repoFullName = getSingleSourceId(input.sourceIds, 'GitHub Intake requires exactly one repository source.');\n const page = parsePositiveCursor(input.cursor);\n const labels = normalizeLabels(input.labels);\n const result = await this.listRepoOpenIssues(installationId, repoFullName, page, {\n label: labels.length > 0 ? labels.join(',') : undefined,\n });\n return {\n issues: result.issues.map(issue => ({\n id: String(issue.number),\n identifier: `#${issue.number}`,\n title: issue.title,\n url: issue.url,\n author: issue.author,\n state: 'open',\n stateType: 'open',\n priority: null,\n assignee: null,\n source: repoFullName,\n labels: issue.labels,\n commentCount: issue.comments,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n })),\n nextCursor: result.nextPage === null ? null : String(result.nextPage),\n };\n }\n\n async #getIntakeIssue(input: GetIntakeIssueInput): Promise<IntakeIssueDetail | null> {\n const installationId = getGithubInstallationId(input.connection);\n const repoFullName = requireSourceId(input.sourceId, 'GitHub Intake requires a repository source.');\n const parts = splitRepoFullName(repoFullName);\n const issueNumber = parsePositiveInteger(input.issueId);\n if (!parts || issueNumber === null) return null;\n const octokit = this.getInstallationOctokit(installationId);\n try {\n const [{ data: issue }, comments] = await Promise.all([\n octokit.issues.get({ owner: parts.owner, repo: parts.repo, issue_number: issueNumber }),\n octokit.paginate(octokit.issues.listComments, {\n owner: parts.owner,\n repo: parts.repo,\n issue_number: issueNumber,\n per_page: 100,\n }),\n ]);\n if (issue.pull_request) return null;\n return {\n id: String(issue.number),\n identifier: `#${issue.number}`,\n title: issue.title,\n url: issue.html_url,\n author: issue.user?.login ?? null,\n state: issue.state,\n stateType: issue.state,\n priority: null,\n assignee: issue.assignee?.login ?? null,\n source: repoFullName,\n labels: issue.labels.map(label => (typeof label === 'string' ? label : (label.name ?? ''))).filter(Boolean),\n commentCount: issue.comments,\n createdAt: issue.created_at,\n updatedAt: issue.updated_at,\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.created_at,\n })),\n };\n } catch (err) {\n if (isNotFoundError(err)) return null;\n throw err;\n }\n }\n\n async #updateIntakeIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> {\n const installationId = getGithubInstallationId(input.connection);\n const repoFullName = requireSourceId(input.sourceId, 'GitHub Intake requires a repository source.');\n const parts = splitRepoFullName(repoFullName);\n const issueNumber = parsePositiveInteger(input.issueId);\n if (!parts || issueNumber === null) return null;\n // GitHub has no custom workflow states; only open/closed. `byName` is a\n // no-op with a warn log.\n if (input.state.kind === 'byName') {\n console.warn(`GitHub integration: 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 const octokit = this.getInstallationOctokit(installationId);\n try {\n // Pre-flight: Factory does not close pull requests via `updateIssue`.\n // PR merges/closes belong to the version-control pipeline.\n const { data: current } = await octokit.issues.get({\n owner: parts.owner,\n repo: parts.repo,\n issue_number: issueNumber,\n });\n if (current.pull_request) {\n console.warn(\n `GitHub integration: updateIssue rejected — target ${repoFullName}#${issueNumber} is a pull request.`,\n );\n return null;\n }\n const { data: issue } = await octokit.issues.update({\n owner: parts.owner,\n repo: parts.repo,\n issue_number: issueNumber,\n state: targetState,\n ...(stateReason ? { state_reason: stateReason } : {}),\n });\n return {\n id: String(issue.number),\n identifier: `#${issue.number}`,\n title: issue.title,\n url: issue.html_url,\n author: issue.user?.login ?? null,\n state: issue.state,\n stateType: issue.state,\n priority: null,\n assignee: issue.assignee?.login ?? null,\n source: repoFullName,\n labels: issue.labels.map(label => (typeof label === 'string' ? label : (label.name ?? ''))).filter(Boolean),\n commentCount: issue.comments,\n createdAt: issue.created_at,\n updatedAt: issue.updated_at,\n };\n } catch (err) {\n if (isNotFoundError(err)) return null;\n throw err;\n }\n }\n\n async #createIntakeComment(input: CreateIntakeCommentInput): Promise<{ id: string; url: string } | null> {\n const installationId = getGithubInstallationId(input.connection);\n const repoFullName = requireSourceId(input.sourceId, 'GitHub Intake requires a repository source.');\n const parts = splitRepoFullName(repoFullName);\n const issueNumber = parsePositiveInteger(input.issueId);\n if (!parts || issueNumber === null) return null;\n const octokit = this.getInstallationOctokit(installationId);\n try {\n const { data } = await octokit.issues.createComment({\n owner: parts.owner,\n repo: parts.repo,\n issue_number: issueNumber,\n body: input.body,\n });\n return { id: String(data.id), url: data.html_url };\n } catch (err) {\n if (isNotFoundError(err)) return null;\n throw err;\n }\n }\n\n #repositoryClient(connection: IntegrationConnection, sourceId: string) {\n const installationId = getGithubInstallationId(connection);\n const parts = splitRepoFullName(sourceId);\n if (!parts) throw new Error('GitHub pull requests require an owner/repository source.');\n return { octokit: this.getInstallationOctokit(installationId), parts };\n }\n\n async #listPullRequests(input: InputOf<'listPullRequests'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const page = parsePositiveCursor(input.cursor);\n const response = await octokit.pulls.list({\n ...parts,\n state: input.state ?? 'open',\n per_page: LIST_PAGE_SIZE,\n page,\n });\n const pullRequests = response.data\n .filter(pr => input.includeDrafts !== false || !pr.draft)\n .map(pr => parsePullRequest(pr));\n return {\n pullRequests,\n nextCursor: response.data.length === LIST_PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #getPullRequest(input: InputOf<'getPullRequest'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const pullNumber = requirePullRequestNumber(input.pullRequestId);\n try {\n const { data } = await octokit.pulls.get({ ...parts, pull_number: pullNumber });\n return parsePullRequest(data);\n } catch (err) {\n if (isNotFoundError(err)) return null;\n throw err;\n }\n }\n\n async #createPullRequest(input: InputOf<'createPullRequest'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.create({\n ...parts,\n title: input.title,\n body: input.body,\n base: input.baseBranch,\n head: input.headBranch,\n draft: input.draft,\n });\n return parsePullRequest(data);\n }\n\n async #updatePullRequest(input: InputOf<'updatePullRequest'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.update({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n title: input.title,\n body: input.body === null ? '' : input.body,\n base: input.baseBranch,\n state: input.state,\n });\n return parsePullRequest(data);\n }\n\n async #closePullRequest(input: InputOf<'closePullRequest'>) {\n return this.#updatePullRequest({ ...input, state: 'closed' });\n }\n\n async #mergePullRequest(input: InputOf<'mergePullRequest'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.merge({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n commit_title: input.commitTitle,\n commit_message: input.commitMessage,\n merge_method: input.method,\n });\n return { merged: data.merged, message: data.message, sha: data.sha ?? null };\n }\n\n async #listComments(input: InputOf<'listComments'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const page = parsePositiveCursor(input.cursor);\n const response = await octokit.issues.listComments({\n ...parts,\n issue_number: requirePullRequestNumber(input.pullRequestId),\n per_page: LIST_PAGE_SIZE,\n page,\n });\n return {\n comments: response.data.map(comment => parsePullRequestComment(comment)),\n nextCursor: response.data.length === LIST_PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #createComment(input: InputOf<'createComment'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.issues.createComment({\n ...parts,\n issue_number: requirePullRequestNumber(input.pullRequestId),\n body: input.body,\n });\n return parsePullRequestComment(data);\n }\n\n async #updateComment(input: InputOf<'updateComment'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.issues.updateComment({\n ...parts,\n comment_id: requirePositiveId(input.commentId, 'comment'),\n body: input.body,\n });\n return parsePullRequestComment(data);\n }\n\n async #deleteComment(input: InputOf<'deleteComment'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n await octokit.issues.deleteComment({ ...parts, comment_id: requirePositiveId(input.commentId, 'comment') });\n }\n\n async #listReviews(input: InputOf<'listReviews'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const page = parsePositiveCursor(input.cursor);\n const response = await octokit.pulls.listReviews({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n per_page: LIST_PAGE_SIZE,\n page,\n });\n return {\n reviews: response.data.map(review => parseReview(review)),\n nextCursor: response.data.length === LIST_PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #getReview(input: InputOf<'getReview'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n try {\n const { data } = await octokit.pulls.getReview({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n review_id: requirePositiveId(input.reviewId, 'review'),\n });\n return parseReview(data);\n } catch (err) {\n if (isNotFoundError(err)) return null;\n throw err;\n }\n }\n\n async #createReview(input: InputOf<'createReview'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.createReview({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n body: input.body,\n commit_id: input.commitId,\n event: input.event ? reviewEventToGithub(input.event) : undefined,\n });\n return parseReview(data);\n }\n\n async #updateReview(input: InputOf<'updateReview'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.updateReview({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n review_id: requirePositiveId(input.reviewId, 'review'),\n body: input.body,\n });\n return parseReview(data);\n }\n\n async #submitReview(input: InputOf<'submitReview'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.submitReview({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n review_id: requirePositiveId(input.reviewId, 'review'),\n body: input.body,\n event: reviewEventToGithub(input.event),\n });\n return parseReview(data);\n }\n\n async #dismissReview(input: InputOf<'dismissReview'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.dismissReview({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n review_id: requirePositiveId(input.reviewId, 'review'),\n message: input.message,\n });\n return parseReview(data);\n }\n\n async #deletePendingReview(input: InputOf<'deletePendingReview'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n await octokit.pulls.deletePendingReview({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n review_id: requirePositiveId(input.reviewId, 'review'),\n });\n }\n\n async #listReviewComments(input: InputOf<'listReviewComments'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const page = parsePositiveCursor(input.cursor);\n const response = await octokit.pulls.listReviewComments({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n per_page: LIST_PAGE_SIZE,\n page,\n });\n return {\n comments: response.data.map(comment => parseReviewComment(comment)),\n nextCursor: response.data.length === LIST_PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #createReviewComment(input: InputOf<'createReviewComment'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const pullNumber = requirePullRequestNumber(input.pullRequestId);\n if (input.replyToId) {\n const { data } = await octokit.pulls.createReplyForReviewComment({\n ...parts,\n pull_number: pullNumber,\n comment_id: requirePositiveId(input.replyToId, 'review comment'),\n body: input.body,\n });\n return parseReviewComment(data);\n }\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 if ((input.startLine === undefined) !== (input.startSide === undefined)) {\n throw new Error('A multi-line review comment requires both startLine and startSide.');\n }\n const { data } = await octokit.pulls.createReviewComment({\n ...parts,\n pull_number: pullNumber,\n body: input.body,\n commit_id: input.commitId,\n path: input.path,\n line: input.line,\n side: input.side.toUpperCase() as 'LEFT' | 'RIGHT',\n start_line: input.startLine,\n start_side: input.startSide?.toUpperCase() as 'LEFT' | 'RIGHT' | undefined,\n });\n return parseReviewComment(data);\n }\n\n async #updateReviewComment(input: InputOf<'updateReviewComment'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.updateReviewComment({\n ...parts,\n comment_id: requirePositiveId(input.commentId, 'review comment'),\n body: input.body,\n });\n return parseReviewComment(data);\n }\n\n async #deleteReviewComment(input: InputOf<'deleteReviewComment'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n await octokit.pulls.deleteReviewComment({\n ...parts,\n comment_id: requirePositiveId(input.commentId, 'review comment'),\n });\n }\n\n async #listRequestedReviewers(input: InputOf<'listRequestedReviewers'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.listRequestedReviewers({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n });\n return parseRequestedReviewers(data);\n }\n\n async #requestReviewers(input: InputOf<'requestReviewers'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.requestReviewers({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n reviewers: input.users ?? [],\n team_reviewers: input.teams ?? [],\n });\n return parseRequestedReviewers(data);\n }\n\n async #removeReviewers(input: InputOf<'removeRequestedReviewers'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.removeRequestedReviewers({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n reviewers: input.users ?? [],\n team_reviewers: input.teams ?? [],\n });\n return parseRequestedReviewers(data);\n }\n\n /** Add labels to an issue (deduplicated; no-op on empty/malformed input). */\n async addIssueLabels(\n installationId: number,\n repoFullName: string,\n issueNumber: number,\n labels: string[],\n ): Promise<void> {\n const parts = splitRepoFullName(repoFullName);\n if (!parts) return;\n const uniqueLabels = [...new Set(labels.map(label => label.trim()).filter(Boolean))];\n if (uniqueLabels.length === 0) return;\n const octokit = this.getInstallationOctokit(installationId);\n await octokit.issues.addLabels({\n owner: parts.owner,\n repo: parts.repo,\n issue_number: issueNumber,\n labels: uniqueLabels,\n });\n }\n\n /**\n * List one page of a repo's open issues through an installation token. The\n * issues API also returns pull requests, so those are filtered out (the\n * filter can make a non-final page shorter than the page size — `nextPage`\n * is derived from the raw response length, not the filtered one).\n */\n async listRepoOpenIssues(\n installationId: number,\n repoFullName: string,\n page: number,\n options: ListRepoOpenIssuesOptions = {},\n ): Promise<IssuePage> {\n const parts = splitRepoFullName(repoFullName);\n if (!parts) return { issues: [], nextPage: null };\n const octokit = this.getInstallationOctokit(installationId);\n const response = await octokit.issues.listForRepo({\n owner: parts.owner,\n repo: parts.repo,\n state: 'open',\n labels: options.label,\n per_page: LIST_PAGE_SIZE,\n page,\n });\n const issues = response.data\n .filter(issue => !issue.pull_request)\n .map(issue => ({\n number: issue.number,\n title: issue.title,\n url: issue.html_url,\n author: issue.user?.login ?? null,\n labels: issue.labels.map(label => (typeof label === 'string' ? label : (label.name ?? ''))).filter(Boolean),\n comments: issue.comments,\n createdAt: issue.created_at,\n updatedAt: issue.updated_at,\n }));\n return { issues, nextPage: response.data.length === LIST_PAGE_SIZE ? page + 1 : null };\n }\n\n /**\n * Build the GitHub App install URL. `state` is carried through the install\n * flow and validated on callback.\n */\n buildInstallUrl(state: string): string {\n const url = new URL(`https://github.com/apps/${this.#slug}/installations/new`);\n url.searchParams.set('state', state);\n return url.toString();\n }\n\n /**\n * Build the OAuth identify URL (authorize) used to confirm the user's\n * identity and obtain a user token for listing their installations.\n */\n buildOAuthIdentifyUrl(state: string, redirectUri: string): string {\n const url = new URL('https://github.com/login/oauth/authorize');\n url.searchParams.set('client_id', this.#clientId);\n url.searchParams.set('redirect_uri', redirectUri);\n url.searchParams.set('state', state);\n return url.toString();\n }\n\n /** Exchange an OAuth `code` for a user access token. */\n async exchangeOAuthCode(code: string, redirectUri: string): Promise<string> {\n const res = await fetch('https://github.com/login/oauth/access_token', {\n method: 'POST',\n signal: AbortSignal.timeout(10_000),\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({\n client_id: this.#clientId,\n client_secret: this.#clientSecret,\n code,\n redirect_uri: redirectUri,\n }),\n });\n if (!res.ok) {\n throw new Error(`GitHub OAuth token exchange failed: ${res.status}`);\n }\n const data = (await res.json()) as { access_token?: string; error?: string; error_description?: string };\n if (!data.access_token) {\n throw new Error(\n `GitHub OAuth token exchange returned no token: ${data.error_description ?? data.error ?? 'unknown'}`,\n );\n }\n return data.access_token;\n }\n\n /**\n * The integration's HTTP surface: the `/web/github/*` + `/auth/github/*`\n * Mastra `apiRoutes` (webhook handler, install/OAuth flow, project +\n * worktree + session operations). The factory folds these into the server's\n * `apiRoutes` when the feature is ready. Handlers operate on this instance.\n */\n routes(ctx: IntegrationContext): ApiRoute[] {\n this.#storage = ctx.storage;\n const ingestFactoryEvent = attachGithubRules(this, ctx);\n return buildGithubRoutes({\n github: this,\n auth: ctx.auth,\n fleet: ctx.fleet,\n storage: ctx.factoryStorage,\n stateSigner: ctx.stateSigner,\n baseUrl: ctx.baseUrl,\n controller: ctx.controller,\n runIssueTriage: ctx.controller\n ? input => runGithubIssueTriage({ controller: ctx.controller!, input })\n : undefined,\n emitAudit: ctx.hooks?.emitAudit,\n projects: ctx.storage.projects,\n ingestFactoryEvent,\n });\n }\n\n /**\n * Merge-state safety net. Webhooks are the only other writer of merge state,\n * and a self-hosted deployment GitHub cannot reach (private network, local\n * dev) never receives one — without this sweep its PR cards stay open\n * forever. Disable with `MASTRACODE_GITHUB_RECONCILE_ENABLED=false`.\n */\n workers(ctx: IntegrationContext): MastraWorker[] {\n if (process.env.MASTRACODE_GITHUB_RECONCILE_ENABLED?.trim().toLowerCase() === 'false') return [];\n const reconcile = attachGithubReconciler(this, ctx, input => this.fetchPullRequestState(input));\n if (!reconcile) return [];\n const intervalMs = Number(process.env.MASTRACODE_GITHUB_RECONCILE_INTERVAL_MS);\n return [\n new GithubReconcileWorker({\n reconcile,\n sourceControl: ctx.storage.sourceControl,\n ...(Number.isSafeInteger(intervalMs) && intervalMs > 0 ? { intervalMs } : {}),\n }),\n ];\n }\n\n /**\n * Reads live PR state for the merge reconciler. Returns undefined when the PR\n * cannot be resolved 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 try {\n const pullRequest = await this.#getPullRequest({\n connection: { type: 'app-installation', installationId: input.installationId },\n sourceId: input.repository,\n pullRequestId: String(input.number),\n });\n if (!pullRequest) return undefined;\n return {\n title: pullRequest.title,\n url: pullRequest.url,\n state: pullRequest.state === 'closed' ? 'closed' : 'open',\n merged: pullRequest.merged,\n headBranch: pullRequest.headBranch,\n baseBranch: pullRequest.baseBranch,\n ...(pullRequest.createdAt ? { createdAt: pullRequest.createdAt } : {}),\n };\n } catch {\n return undefined;\n }\n }\n\n /**\n * Session-scoped agent tools for token refresh and PR subscriptions in\n * sessions bound to a GitHub-backed project. Empty elsewhere.\n */\n sessionTools({ requestContext }: { requestContext: RequestContext }): IntegrationTools {\n return createGithubSubscriptionTools(requestContext, this);\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(requestContext, pullRequestUrl, 'auto-gh-pr-create', this);\n }\n\n /** Non-secret config snapshot for system diagnostics/startup logs. */\n diagnostics(): Record<string, unknown> {\n return {\n slug: this.#slug,\n webhookSecretConfigured: this.#webhookSecret !== undefined,\n };\n }\n}\n\ninterface GithubPullRequestData {\n number: number;\n title: string;\n html_url: string;\n user: { login?: string } | null;\n body?: string | null;\n state: string;\n draft?: boolean | null;\n merged?: boolean;\n merged_at?: string | null;\n mergeable?: boolean | null;\n base: { ref: string };\n head: { ref: string; sha: string };\n created_at: string;\n updated_at: string;\n}\n\ninterface GithubCommentData {\n id: number;\n html_url: string;\n user: { login?: string } | null;\n body?: string | null;\n created_at: string;\n updated_at: string;\n}\n\ninterface GithubReviewData {\n id: number;\n html_url?: string;\n user: { login?: string } | null;\n body?: string | null;\n state: string;\n commit_id?: string | null;\n submitted_at?: string | null;\n}\n\ninterface GithubReviewCommentData extends GithubCommentData {\n path: string;\n line?: number | null;\n side?: string | null;\n commit_id: string;\n in_reply_to_id?: number | null;\n}\n\nfunction parsePullRequest(pr: GithubPullRequestData): PullRequest {\n return {\n id: String(pr.number),\n title: pr.title,\n url: pr.html_url,\n author: pr.user?.login ?? null,\n body: pr.body?.trim() ? pr.body : null,\n state: pr.state === 'closed' ? 'closed' : 'open',\n draft: pr.draft ?? false,\n merged: pr.merged ?? Boolean(pr.merged_at),\n mergeable: typeof pr.mergeable === 'boolean' ? pr.mergeable : null,\n baseBranch: pr.base.ref,\n headBranch: pr.head.ref,\n headSha: pr.head.sha,\n createdAt: pr.created_at,\n updatedAt: pr.updated_at,\n };\n}\n\nfunction parsePullRequestComment(comment: GithubCommentData): PullRequestComment {\n return {\n id: String(comment.id),\n url: comment.html_url,\n author: comment.user?.login ?? null,\n body: comment.body ?? '',\n createdAt: comment.created_at,\n updatedAt: comment.updated_at,\n };\n}\n\nfunction parseReview(review: GithubReviewData): Review {\n return {\n id: String(review.id),\n url: review.html_url ?? null,\n author: review.user?.login ?? null,\n body: review.body?.trim() ? review.body : null,\n state: parseReviewState(review.state),\n commitId: review.commit_id ?? null,\n submittedAt: review.submitted_at ?? null,\n };\n}\n\nfunction parseReviewComment(comment: GithubReviewCommentData): ReviewComment {\n const parsed = parsePullRequestComment(comment);\n const side = comment.side?.toLowerCase();\n return {\n ...parsed,\n path: comment.path,\n line: comment.line ?? null,\n side: side === 'left' || side === 'right' ? side : null,\n commitId: comment.commit_id,\n replyToId: comment.in_reply_to_id ? String(comment.in_reply_to_id) : null,\n };\n}\n\nfunction parseRequestedReviewers(data: {\n users?: Array<{ login?: string }> | null;\n teams?: Array<{ slug?: string }> | null;\n requested_reviewers?: Array<{ login?: string }> | null;\n requested_teams?: Array<{ slug?: string }> | null;\n}) {\n return {\n users: (data.users ?? data.requested_reviewers ?? []).flatMap(user => (user.login ? [user.login] : [])),\n teams: (data.teams ?? data.requested_teams ?? []).flatMap(team => (team.slug ? [team.slug] : [])),\n };\n}\n\nfunction parseReviewState(state: string): Review['state'] {\n if (state === 'PENDING') return 'pending';\n if (state === 'COMMENTED') return 'commented';\n if (state === 'APPROVED') return 'approved';\n if (state === 'CHANGES_REQUESTED') return 'changes-requested';\n if (state === 'DISMISSED') return 'dismissed';\n throw new Error(`Unsupported GitHub review state: ${state}`);\n}\n\nfunction reviewEventToGithub(event: Exclude<InputOf<'createReview'>['event'], undefined>) {\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 requirePullRequestNumber(value: string): number {\n return requirePositiveId(value, 'pull request');\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 getGithubInstallationId(connection: IntegrationConnection): number {\n if (connection.type !== 'app-installation') {\n throw new Error('GitHub capabilities require an app-installation connection.');\n }\n return connection.installationId;\n}\n\nfunction getSingleSourceId(sourceIds: string[], message: string): string {\n if (sourceIds.length !== 1) throw new Error(message);\n return sourceIds[0]!;\n}\n\nfunction normalizeLabels(labels: string[] | undefined): string[] {\n return [...new Set((labels ?? []).map(label => label.trim()).filter(Boolean))];\n}\n\nfunction requireSourceId(sourceId: string | undefined, message: string): string {\n if (!sourceId) throw new Error(message);\n return sourceId;\n}\n\nfunction parsePositiveCursor(cursor: string | undefined): number {\n if (cursor === undefined) return 1;\n const page = parsePositiveInteger(cursor);\n if (page === null) throw new Error('GitHub cursor must be a positive page number.');\n return page;\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 isNotFoundError(error: unknown): boolean {\n return typeof error === 'object' && error !== null && 'status' in error && error.status === 404;\n}\n\n/** Split an `owner/name` full name into its parts, or `null` when malformed. */\nfunction splitRepoFullName(repoFullName: string): { owner: string; repo: string } | null {\n const slash = repoFullName.indexOf('/');\n if (slash <= 0 || slash === repoFullName.length - 1) return null;\n return { owner: repoFullName.slice(0, slash), repo: repoFullName.slice(slash + 1) };\n}\n\nfunction parseGithubExternalTarget(externalId: string): { repositoryId: string; issueId: string } | null {\n const match = externalId.match(/^github:(\\d+):(?:issue|pull-request):(\\d+)$/) ?? externalId.match(/^(\\d+):(\\d+)$/);\n if (!match?.[1] || !match[2]) return null;\n const repositoryId = parsePositiveInteger(match[1]);\n const issueId = parsePositiveInteger(match[2]);\n return repositoryId && issueId ? { repositoryId: String(repositoryId), issueId: String(issueId) } : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyEA,SAAgB,oBAAoB,KAAqB;CACvD,MAAM,MAAM,IAAI,QAAQ,QAAQ,IAAI;CACpC,IAAI,IAAI,SAAS,IAAI,GAAG,OAAO;CAC/B,MAAM,YAAY,IAAI,KAAK,CAAC,CAAC,MAAM,qEAAqE;CACxG,IAAI,CAAC,WAAW,OAAO;CACvB,MAAM,OAAO,UAAU,EAAE,CAAE,QAAQ,QAAQ,EAAE;CAC7C,OAAO,GAAG,UAAU,GAAG,IAAI,KAAK,MAAM,UAAU,CAAC,CAAE,KAAK,IAAI,EAAE,IAAI,UAAU,GAAG;AACjF;;AAgCA,MAAa,iBAAiB;;AAmC9B,MAAM,kBAAkB;CAAC;CAAS;CAAc;CAAY;CAAgB;AAAM;AAElF,IAAa,oBAAb,MAA6D;;CAE3D,KAAc;CACd,SAA0B;EACxB,wBAAuB,UAAS,KAAKA,uBAAuB,KAAK;EACjE,aAAa,OAAO,EAAE,YAAY;GAChC,MAAM,gBAAgB,MAAM,KAAK,qBAAqB,cAAc,KAAK,EAAE,MA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,SAAS,kBAAkB,cAA8D;CACvF,MAAM,QAAQ,aAAa,QAAQ,GAAG;CACtC,IAAI,SAAS,KAAK,UAAU,aAAa,SAAS,GAAG,OAAO;CAC5D,OAAO;EAAE,OAAO,aAAa,MAAM,GAAG,KAAK;EAAG,MAAM,aAAa,MAAM,QAAQ,CAAC;CAAE;AACpF;AAEA,SAAS,0BAA0B,YAAsE;CACvG,MAAM,QAAQ,WAAW,MAAM,6CAA6C,KAAK,WAAW,MAAM,eAAe;CACjH,IAAI,CAAC,QAAQ,MAAM,CAAC,MAAM,IAAI,OAAO;CACrC,MAAM,eAAe,qBAAqB,MAAM,EAAE;CAClD,MAAM,UAAU,qBAAqB,MAAM,EAAE;CAC7C,OAAO,gBAAgB,UAAU;EAAE,cAAc,OAAO,YAAY;EAAG,SAAS,OAAO,OAAO;CAAE,IAAI;AACtG"}
|
|
1
|
+
{"version":3,"file":"integration.js","names":["#resolveIntakeDispatch","#listIntakeIssues","#getIntakeIssue","#createIntakeComment","#updateIntakeIssue","#sourceControlStorage","#listPullRequests","#getPullRequest","#createPullRequest","#updatePullRequest","#closePullRequest","#mergePullRequest","#listComments","#createComment","#updateComment","#deleteComment","#listReviews","#getReview","#createReview","#updateReview","#submitReview","#dismissReview","#deletePendingReview","#listReviewComments","#createReviewComment","#updateReviewComment","#deleteReviewComment","#listRequestedReviewers","#requestReviewers","#removeReviewers","#appId","#privateKey","#clientId","#clientSecret","#slug","#webhookSecret","#storage","#appAuth","#repositoryClient"],"sources":["../../../src/integrations/github/integration.ts"],"sourcesContent":["/**\n * `GithubIntegration` — the injectable GitHub App integration for the web\n * factory.\n *\n * The deploy entry (`src/mastra/index.ts`) reads the `GITHUB_APP_*` env vars\n * once, constructs an instance, and passes it to `MastraFactory` (the same\n * dependency-injection pattern as the auth adapter and the sandbox machine).\n * The factory seeds it into the runtime-config registry for the feature gate\n * (`./config.ts`) and hands the instance to every consumer explicitly — route\n * handlers receive it through `routes()`, the webhook fan-out and session\n * subscription tools through their deps.\n *\n * The class owns:\n * - the GitHub App credentials (validated + PEM-normalized at construction),\n * - every GitHub API operation the web surface performs (Octokit factories,\n * token minting, installation/repo/issue/PR listings, OAuth exchange),\n * - the webhook secret used to verify GitHub webhook deliveries,\n * - its own HTTP surface: `routes()` returns the `/web/github/*` +\n * `/auth/github/*` Mastra `apiRoutes`.\n *\n * A custom integration (different app per tenant, custom Octokit config) can\n * subclass this and override individual methods — everything downstream only\n * talks to the instance.\n */\n\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\nimport { createAppAuth } from '@octokit/auth-app';\nimport { Octokit } from '@octokit/rest';\n\nimport type { IntegrationConnection } from '../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n ListIntakeIssuesInput,\n UpdateIntakeIssueInput,\n} from '../../capabilities/intake.js';\nimport type {\n PullRequest,\n PullRequestComment,\n Review,\n ReviewComment,\n VersionControl,\n} from '../../capabilities/version-control.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { runGithubIssueTriage } from './issue-triage.js';\nimport { GithubReconcileWorker } from './reconcile-worker.js';\nimport { buildGithubRoutes } from './routes.js';\nimport { attachGithubReconciler, attachGithubRules } from './rules.js';\nimport type { ReconcilePullRequestState } from './rules.js';\nimport {\n createGithubSubscriptionTools,\n parseCreatedPullRequest,\n subscribeCurrentSessionToPullRequest,\n} from './session-subscriptions.js';\nimport type { GithubSubscriptionStorage } from './subscriptions.js';\n\ntype InputOf<TMethod extends keyof VersionControl> = VersionControl[TMethod] extends (input: infer TInput) => unknown\n ? TInput\n : never;\n\n/**\n * Normalize a PEM private key supplied via env. Env tooling tends to mangle\n * multi-line PEMs, so two single-line forms are supported:\n * - `\\n`-escaped: literal `\\n` sequences become real newlines\n * - fully flattened: newlines stripped entirely — the PEM is rebuilt by\n * re-wrapping the base64 body (Node's decoder rejects header/body/footer\n * on one line with `error:1E08010C:DECODER routines::unsupported`)\n */\nexport function normalizePrivateKey(raw: string): string {\n const key = raw.replace(/\\\\n/g, '\\n');\n if (key.includes('\\n')) return key;\n const flattened = key.trim().match(/^(-----BEGIN [A-Z0-9 ]+-----)\\s*(.+?)\\s*(-----END [A-Z0-9 ]+-----)$/);\n if (!flattened) return key;\n const body = flattened[2]!.replace(/\\s+/g, '');\n return `${flattened[1]}\\n${body.match(/.{1,64}/g)!.join('\\n')}\\n${flattened[3]}\\n`;\n}\n\nexport interface UserInstallation {\n installationId: number;\n accountLogin: string | null;\n accountType: string | null;\n}\n\nexport interface RepoSummary {\n id: number;\n fullName: string;\n name: string;\n owner: string;\n defaultBranch: string;\n private: boolean;\n installationId: number;\n}\n\nexport type GithubRepositoryPermission = 'admin' | 'maintain' | 'write' | 'triage' | 'read' | 'none';\n\nexport interface IssueSummary {\n number: number;\n title: string;\n url: string;\n author: string | null;\n assignees: string[];\n labels: string[];\n comments: number;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Page size for issue/PR listings; one GitHub API call per page. */\nexport const LIST_PAGE_SIZE = 30;\n\nexport interface IssuePage {\n issues: IssueSummary[];\n /** Next page number to request, or `null` when this was the last page. */\n nextPage: number | null;\n}\n\nexport interface ListRepoOpenIssuesOptions {\n label?: string;\n}\n\nexport interface GithubIntegrationConfig {\n /** GitHub App id (the numeric id, as a string). */\n appId: string;\n /**\n * App private key (PEM). Multi-line, `\\n`-escaped, and fully flattened\n * single-line forms are all accepted (normalized at construction).\n */\n privateKey: string;\n /** OAuth client id of the GitHub App. */\n clientId: string;\n /** OAuth client secret of the GitHub App. */\n clientSecret: string;\n /** App slug — the URL name used to build the install URL. */\n slug: string;\n /**\n * Secret GitHub uses to sign webhook deliveries. Omitted → webhook\n * signature verification rejects all deliveries. Also serves as the default\n * replica-stable OAuth/install `state` secret (see `./config.ts`).\n */\n webhookSecret?: string;\n}\n\n/** Human-readable names of the required config fields, for construction errors. */\nconst REQUIRED_FIELDS = ['appId', 'privateKey', 'clientId', 'clientSecret', 'slug'] as const;\n\nexport class GithubIntegration implements FactoryIntegration {\n /** Stable integration identifier (see `../factory-integration.ts`). */\n readonly id = 'github';\n readonly intake: Intake = {\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: async ({ orgId }) => {\n const installations = await this.sourceControlStorage.installations.list({ orgId });\n const repositories = await Promise.all(\n installations.map(installation =>\n this.sourceControlStorage.repositories.list({ orgId, installationId: installation.id }),\n ),\n );\n return repositories.flat().map(repository => ({\n id: repository.id,\n name: repository.slug,\n type: 'repository',\n metadata: { defaultBranch: repository.defaultBranch },\n }));\n },\n listItems: async ({ orgId, sourceIds, cursor }) => {\n const page = cursor ? Number.parseInt(cursor, 10) : 1;\n const requestedPage = Number.isSafeInteger(page) && page > 0 ? page : 1;\n const pages = await Promise.all(\n sourceIds.map(async sourceId => {\n const repository = await this.sourceControlStorage.repositories.get({ orgId, id: sourceId });\n if (!repository) return { items: [], hasNextPage: false };\n const installation = await this.sourceControlStorage.installations.get({\n orgId,\n id: repository.installationId,\n });\n if (!installation) return { items: [], hasNextPage: false };\n const installationId = Number.parseInt(installation.externalId, 10);\n if (!Number.isSafeInteger(installationId)) return { items: [], hasNextPage: false };\n const [issues, pullRequests] = await Promise.all([\n this.listRepoOpenIssues(installationId, repository.slug, requestedPage),\n this.versionControl.listPullRequests({\n connection: { type: 'app-installation', installationId },\n sourceId: repository.slug,\n includeDrafts: false,\n cursor: String(requestedPage),\n }),\n ]);\n return {\n items: [\n ...issues.issues.map(issue => ({\n source: { type: 'issue', externalId: `${repository.externalId}:${issue.number}`, url: issue.url },\n sourceId: repository.id,\n title: issue.title,\n status: 'open',\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n metadata: { repository: repository.slug, number: issue.number, author: issue.author },\n })),\n ...pullRequests.pullRequests.map(pullRequest => ({\n source: {\n type: 'pull-request',\n externalId: `${repository.externalId}:${pullRequest.id}`,\n url: pullRequest.url,\n },\n sourceId: repository.id,\n title: pullRequest.title,\n status: 'open',\n createdAt: pullRequest.createdAt,\n updatedAt: pullRequest.updatedAt,\n metadata: {\n repository: repository.slug,\n number: Number(pullRequest.id),\n author: pullRequest.author,\n baseBranch: pullRequest.baseBranch,\n headBranch: pullRequest.headBranch,\n },\n })),\n ],\n hasNextPage: issues.nextPage !== null || pullRequests.nextCursor !== null,\n };\n }),\n );\n return {\n items: pages.flatMap(result => result.items),\n nextCursor: pages.some(result => result.hasNextPage) ? String(requestedPage + 1) : null,\n };\n },\n listIssues: input => this.#listIntakeIssues(input),\n getIssue: input => this.#getIntakeIssue(input),\n createComment: input => this.#createIntakeComment(input),\n updateIssue: input => this.#updateIntakeIssue(input),\n };\n readonly versionControl: VersionControl = {\n initialize: ({ storage }) => {\n this.#sourceControlStorage = storage;\n },\n registerInstallation: ({ orgId, userId, installation }) =>\n this.sourceControlStorage.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.sourceControlStorage.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 const repository = await this.sourceControlStorage.repositories.get({ orgId, id: repositoryId });\n if (!repository) throw new Error('Version-control repository not found.');\n const installation = await this.sourceControlStorage.installations.get({\n orgId,\n id: repository.installationId,\n });\n if (!installation) throw new Error('Version-control installation not found.');\n const installationId = Number.parseInt(installation.externalId, 10);\n if (!Number.isSafeInteger(installationId)) throw new Error('GitHub installation id is invalid.');\n return {\n cloneUrl: `https://github.com/${repository.slug}.git`,\n authorization: { scheme: 'bearer', token: await this.mintInstallationToken(installationId) },\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.#closePullRequest(input),\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.#listRequestedReviewers(input),\n requestReviewers: input => this.#requestReviewers(input),\n removeRequestedReviewers: input => this.#removeReviewers(input),\n };\n /**\n * The OAuth/install flow round-trips a signed `state` through GitHub, so a\n * multi-replica deploy needs a deployment-stable state secret.\n */\n readonly requiresStableStateSigner = true;\n\n readonly #appId: string;\n readonly #privateKey: string;\n readonly #clientId: string;\n readonly #clientSecret: string;\n readonly #slug: string;\n readonly #webhookSecret: string | undefined;\n #storage: IntegrationContext['storage'] | undefined;\n #sourceControlStorage: IntegrationContext['storage']['sourceControl'] | undefined;\n\n constructor(config: GithubIntegrationConfig) {\n const missing = REQUIRED_FIELDS.filter(field => !config[field]);\n if (missing.length > 0) {\n throw new Error(\n `GithubIntegration: missing required config field(s): ${missing.join(', ')}. ` +\n `Provide the full GitHub App credentials (appId, privateKey, clientId, clientSecret, slug) ` +\n `or omit the integration to disable GitHub-backed repositories.`,\n );\n }\n this.#appId = config.appId;\n this.#privateKey = normalizePrivateKey(config.privateKey);\n this.#clientId = config.clientId;\n this.#clientSecret = config.clientSecret;\n this.#slug = config.slug;\n this.#webhookSecret = config.webhookSecret || undefined;\n }\n\n /** App slug — the URL name used to build the install URL. */\n get slug(): string {\n return this.#slug;\n }\n\n get genericStorage(): IntegrationContext['storage']['generic'] {\n if (!this.#storage) throw new Error('GithubIntegration storage has not been initialized.');\n return this.#storage.generic;\n }\n\n get sourceControlStorage(): IntegrationContext['storage']['sourceControl'] {\n const storage = this.#sourceControlStorage ?? this.#storage?.sourceControl;\n if (!storage) throw new Error('GithubIntegration source-control storage has not been initialized.');\n return storage;\n }\n\n get integrationStorage(): GithubSubscriptionStorage {\n if (!this.#storage) throw new Error('GithubIntegration storage has not been initialized.');\n return this.#storage.generic as unknown as GithubSubscriptionStorage;\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 = await this.sourceControlStorage.repositories.findByExternalId({\n orgId,\n externalId: target.repositoryId,\n });\n if (!repository) return null;\n const installation = await this.sourceControlStorage.installations.get({ orgId, id: repository.installationId });\n if (!installation) return null;\n const installationId = Number.parseInt(installation.externalId, 10);\n if (!Number.isSafeInteger(installationId)) return null;\n return {\n connection: { type: 'app-installation', installationId },\n sourceId: repository.slug,\n issueId: target.issueId,\n };\n }\n\n /** Secret GitHub uses to sign webhook deliveries, when configured. */\n get webhookSecret(): string | undefined {\n return this.#webhookSecret;\n }\n\n #appAuth() {\n return {\n appId: this.#appId,\n privateKey: this.#privateKey,\n clientId: this.#clientId,\n clientSecret: this.#clientSecret,\n };\n }\n\n /**\n * Octokit authenticated as the GitHub App itself (app JWT). Used for\n * app-level operations and to mint installation tokens.\n */\n getAppOctokit(): Octokit {\n return new Octokit({ authStrategy: createAppAuth, auth: this.#appAuth() });\n }\n\n /**\n * Octokit authenticated as a specific installation (installation access\n * token). Used to list repos and to operate on a repo on the user's behalf.\n */\n getInstallationOctokit(installationId: number): Octokit {\n return new Octokit({ authStrategy: createAppAuth, auth: { ...this.#appAuth(), installationId } });\n }\n\n /** Octokit authenticated as a user via their OAuth token (the identify step). */\n getUserOctokit(userToken: string): Octokit {\n return new Octokit({ auth: userToken });\n }\n\n /**\n * Mint a short-lived installation access token. Returned token is used only\n * server-side / inside the sandbox clone URL and never sent to the browser.\n */\n async mintInstallationToken(installationId: number): Promise<string> {\n const auth = createAppAuth(this.#appAuth());\n const installationAuth = await auth({ type: 'installation', installationId });\n return installationAuth.token;\n }\n\n /**\n * List the installations the authenticated user can access, via their OAuth\n * token (`GET /user/installations`).\n */\n async listUserInstallations(userToken: string): Promise<UserInstallation[]> {\n const octokit = this.getUserOctokit(userToken);\n const installations = await octokit.paginate(octokit.apps.listInstallationsForAuthenticatedUser, {\n per_page: 100,\n });\n return installations.map(inst => ({\n installationId: inst.id,\n accountLogin: inst.account && 'login' in inst.account ? inst.account.login : null,\n accountType: inst.account && 'type' in inst.account ? inst.account.type : null,\n }));\n }\n\n /** List repos accessible to an installation (paginated). */\n async listInstallationRepos(installationId: number): Promise<RepoSummary[]> {\n const octokit = this.getInstallationOctokit(installationId);\n const repos = await octokit.paginate(octokit.apps.listReposAccessibleToInstallation, {\n per_page: 100,\n });\n return repos.map(repo => ({\n id: repo.id,\n fullName: repo.full_name,\n name: repo.name,\n owner: repo.owner.login,\n defaultBranch: repo.default_branch,\n private: repo.private,\n installationId,\n }));\n }\n\n /**\n * The authenticated user's permission level on a repo, through the\n * installation. `undefined` when the repo/user is not accessible.\n */\n async getRepositoryCollaboratorPermission(\n installationId: number,\n repoFullName: string,\n username: string,\n signal?: AbortSignal,\n ): Promise<GithubRepositoryPermission | undefined> {\n const parts = splitRepoFullName(repoFullName);\n if (!parts) return undefined;\n try {\n const { data } = await this.getInstallationOctokit(installationId).repos.getCollaboratorPermissionLevel({\n ...parts,\n username,\n request: { signal },\n });\n return data.permission as GithubRepositoryPermission;\n } catch {\n return undefined;\n }\n }\n\n /**\n * Fetch a single repo's metadata through an installation token and confirm\n * the installation actually has access to it. Returns `null` when the repo\n * is not accessible to the installation (so a client can't create a project\n * for an arbitrary repo under an installation id it merely owns).\n */\n async getInstallationRepo(installationId: number, repoFullName: string): Promise<RepoSummary | null> {\n const parts = splitRepoFullName(repoFullName);\n if (!parts) return null;\n const octokit = this.getInstallationOctokit(installationId);\n try {\n const { data } = await octokit.repos.get(parts);\n return {\n id: data.id,\n fullName: data.full_name,\n name: data.name,\n owner: data.owner.login,\n defaultBranch: data.default_branch,\n private: data.private,\n installationId,\n };\n } catch {\n return null;\n }\n }\n\n async #listIntakeIssues(input: ListIntakeIssuesInput): Promise<{ issues: IntakeIssue[]; nextCursor: string | null }> {\n const installationId = getGithubInstallationId(input.connection);\n const repoFullName = getSingleSourceId(input.sourceIds, 'GitHub Intake requires exactly one repository source.');\n const page = parsePositiveCursor(input.cursor);\n const labels = normalizeLabels(input.labels);\n const result = await this.listRepoOpenIssues(installationId, repoFullName, page, {\n label: labels.length > 0 ? labels.join(',') : undefined,\n });\n return {\n issues: result.issues.map(issue => ({\n id: String(issue.number),\n identifier: `#${issue.number}`,\n title: issue.title,\n url: issue.url,\n author: issue.author,\n state: 'open',\n stateType: 'open',\n priority: null,\n assignee: issue.assignees[0] ?? null,\n assignees: issue.assignees,\n source: repoFullName,\n labels: issue.labels,\n commentCount: issue.comments,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n })),\n nextCursor: result.nextPage === null ? null : String(result.nextPage),\n };\n }\n\n async #getIntakeIssue(input: GetIntakeIssueInput): Promise<IntakeIssueDetail | null> {\n const installationId = getGithubInstallationId(input.connection);\n const repoFullName = requireSourceId(input.sourceId, 'GitHub Intake requires a repository source.');\n const parts = splitRepoFullName(repoFullName);\n const issueNumber = parsePositiveInteger(input.issueId);\n if (!parts || issueNumber === null) return null;\n const octokit = this.getInstallationOctokit(installationId);\n try {\n const [{ data: issue }, comments] = await Promise.all([\n octokit.issues.get({ owner: parts.owner, repo: parts.repo, issue_number: issueNumber }),\n octokit.paginate(octokit.issues.listComments, {\n owner: parts.owner,\n repo: parts.repo,\n issue_number: issueNumber,\n per_page: 100,\n }),\n ]);\n if (issue.pull_request) return null;\n return {\n id: String(issue.number),\n identifier: `#${issue.number}`,\n title: issue.title,\n url: issue.html_url,\n author: issue.user?.login ?? null,\n state: issue.state,\n stateType: issue.state,\n priority: null,\n assignee: issue.assignee?.login ?? null,\n assignees: (issue.assignees ?? []).map(user => user.login).filter((login): login is string => Boolean(login)),\n source: repoFullName,\n labels: issue.labels.map(label => (typeof label === 'string' ? label : (label.name ?? ''))).filter(Boolean),\n commentCount: issue.comments,\n createdAt: issue.created_at,\n updatedAt: issue.updated_at,\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.created_at,\n })),\n };\n } catch (err) {\n if (isNotFoundError(err)) return null;\n throw err;\n }\n }\n\n async #updateIntakeIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> {\n const installationId = getGithubInstallationId(input.connection);\n const repoFullName = requireSourceId(input.sourceId, 'GitHub Intake requires a repository source.');\n const parts = splitRepoFullName(repoFullName);\n const issueNumber = parsePositiveInteger(input.issueId);\n if (!parts || issueNumber === null) return null;\n // GitHub has no custom workflow states; only open/closed. `byName` is a\n // no-op with a warn log.\n if (input.state.kind === 'byName') {\n console.warn(`GitHub integration: 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 const octokit = this.getInstallationOctokit(installationId);\n try {\n // Pre-flight: Factory does not close pull requests via `updateIssue`.\n // PR merges/closes belong to the version-control pipeline.\n const { data: current } = await octokit.issues.get({\n owner: parts.owner,\n repo: parts.repo,\n issue_number: issueNumber,\n });\n if (current.pull_request) {\n console.warn(\n `GitHub integration: updateIssue rejected — target ${repoFullName}#${issueNumber} is a pull request.`,\n );\n return null;\n }\n const { data: issue } = await octokit.issues.update({\n owner: parts.owner,\n repo: parts.repo,\n issue_number: issueNumber,\n state: targetState,\n ...(stateReason ? { state_reason: stateReason } : {}),\n });\n return {\n id: String(issue.number),\n identifier: `#${issue.number}`,\n title: issue.title,\n url: issue.html_url,\n author: issue.user?.login ?? null,\n state: issue.state,\n stateType: issue.state,\n priority: null,\n assignee: issue.assignee?.login ?? null,\n assignees: (issue.assignees ?? []).map(user => user.login).filter((login): login is string => Boolean(login)),\n source: repoFullName,\n labels: issue.labels.map(label => (typeof label === 'string' ? label : (label.name ?? ''))).filter(Boolean),\n commentCount: issue.comments,\n createdAt: issue.created_at,\n updatedAt: issue.updated_at,\n };\n } catch (err) {\n if (isNotFoundError(err)) return null;\n throw err;\n }\n }\n\n async #createIntakeComment(input: CreateIntakeCommentInput): Promise<{ id: string; url: string } | null> {\n const installationId = getGithubInstallationId(input.connection);\n const repoFullName = requireSourceId(input.sourceId, 'GitHub Intake requires a repository source.');\n const parts = splitRepoFullName(repoFullName);\n const issueNumber = parsePositiveInteger(input.issueId);\n if (!parts || issueNumber === null) return null;\n const octokit = this.getInstallationOctokit(installationId);\n try {\n const { data } = await octokit.issues.createComment({\n owner: parts.owner,\n repo: parts.repo,\n issue_number: issueNumber,\n body: input.body,\n });\n return { id: String(data.id), url: data.html_url };\n } catch (err) {\n if (isNotFoundError(err)) return null;\n throw err;\n }\n }\n\n #repositoryClient(connection: IntegrationConnection, sourceId: string) {\n const installationId = getGithubInstallationId(connection);\n const parts = splitRepoFullName(sourceId);\n if (!parts) throw new Error('GitHub pull requests require an owner/repository source.');\n return { octokit: this.getInstallationOctokit(installationId), parts };\n }\n\n async #listPullRequests(input: InputOf<'listPullRequests'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const page = parsePositiveCursor(input.cursor);\n const response = await octokit.pulls.list({\n ...parts,\n state: input.state ?? 'open',\n per_page: LIST_PAGE_SIZE,\n page,\n });\n const pullRequests = response.data\n .filter(pr => input.includeDrafts !== false || !pr.draft)\n .map(pr => parsePullRequest(pr));\n return {\n pullRequests,\n nextCursor: response.data.length === LIST_PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #getPullRequest(input: InputOf<'getPullRequest'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const pullNumber = requirePullRequestNumber(input.pullRequestId);\n try {\n const { data } = await octokit.pulls.get({ ...parts, pull_number: pullNumber });\n return parsePullRequest(data);\n } catch (err) {\n if (isNotFoundError(err)) return null;\n throw err;\n }\n }\n\n async #createPullRequest(input: InputOf<'createPullRequest'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.create({\n ...parts,\n title: input.title,\n body: input.body,\n base: input.baseBranch,\n head: input.headBranch,\n draft: input.draft,\n });\n return parsePullRequest(data);\n }\n\n async #updatePullRequest(input: InputOf<'updatePullRequest'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.update({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n title: input.title,\n body: input.body === null ? '' : input.body,\n base: input.baseBranch,\n state: input.state,\n });\n return parsePullRequest(data);\n }\n\n async #closePullRequest(input: InputOf<'closePullRequest'>) {\n return this.#updatePullRequest({ ...input, state: 'closed' });\n }\n\n async #mergePullRequest(input: InputOf<'mergePullRequest'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.merge({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n commit_title: input.commitTitle,\n commit_message: input.commitMessage,\n merge_method: input.method,\n });\n return { merged: data.merged, message: data.message, sha: data.sha ?? null };\n }\n\n async #listComments(input: InputOf<'listComments'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const page = parsePositiveCursor(input.cursor);\n const response = await octokit.issues.listComments({\n ...parts,\n issue_number: requirePullRequestNumber(input.pullRequestId),\n per_page: LIST_PAGE_SIZE,\n page,\n });\n return {\n comments: response.data.map(comment => parsePullRequestComment(comment)),\n nextCursor: response.data.length === LIST_PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #createComment(input: InputOf<'createComment'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.issues.createComment({\n ...parts,\n issue_number: requirePullRequestNumber(input.pullRequestId),\n body: input.body,\n });\n return parsePullRequestComment(data);\n }\n\n async #updateComment(input: InputOf<'updateComment'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.issues.updateComment({\n ...parts,\n comment_id: requirePositiveId(input.commentId, 'comment'),\n body: input.body,\n });\n return parsePullRequestComment(data);\n }\n\n async #deleteComment(input: InputOf<'deleteComment'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n await octokit.issues.deleteComment({ ...parts, comment_id: requirePositiveId(input.commentId, 'comment') });\n }\n\n async #listReviews(input: InputOf<'listReviews'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const page = parsePositiveCursor(input.cursor);\n const response = await octokit.pulls.listReviews({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n per_page: LIST_PAGE_SIZE,\n page,\n });\n return {\n reviews: response.data.map(review => parseReview(review)),\n nextCursor: response.data.length === LIST_PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #getReview(input: InputOf<'getReview'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n try {\n const { data } = await octokit.pulls.getReview({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n review_id: requirePositiveId(input.reviewId, 'review'),\n });\n return parseReview(data);\n } catch (err) {\n if (isNotFoundError(err)) return null;\n throw err;\n }\n }\n\n async #createReview(input: InputOf<'createReview'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.createReview({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n body: input.body,\n commit_id: input.commitId,\n event: input.event ? reviewEventToGithub(input.event) : undefined,\n });\n return parseReview(data);\n }\n\n async #updateReview(input: InputOf<'updateReview'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.updateReview({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n review_id: requirePositiveId(input.reviewId, 'review'),\n body: input.body,\n });\n return parseReview(data);\n }\n\n async #submitReview(input: InputOf<'submitReview'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.submitReview({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n review_id: requirePositiveId(input.reviewId, 'review'),\n body: input.body,\n event: reviewEventToGithub(input.event),\n });\n return parseReview(data);\n }\n\n async #dismissReview(input: InputOf<'dismissReview'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.dismissReview({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n review_id: requirePositiveId(input.reviewId, 'review'),\n message: input.message,\n });\n return parseReview(data);\n }\n\n async #deletePendingReview(input: InputOf<'deletePendingReview'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n await octokit.pulls.deletePendingReview({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n review_id: requirePositiveId(input.reviewId, 'review'),\n });\n }\n\n async #listReviewComments(input: InputOf<'listReviewComments'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const page = parsePositiveCursor(input.cursor);\n const response = await octokit.pulls.listReviewComments({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n per_page: LIST_PAGE_SIZE,\n page,\n });\n return {\n comments: response.data.map(comment => parseReviewComment(comment)),\n nextCursor: response.data.length === LIST_PAGE_SIZE ? String(page + 1) : null,\n };\n }\n\n async #createReviewComment(input: InputOf<'createReviewComment'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const pullNumber = requirePullRequestNumber(input.pullRequestId);\n if (input.replyToId) {\n const { data } = await octokit.pulls.createReplyForReviewComment({\n ...parts,\n pull_number: pullNumber,\n comment_id: requirePositiveId(input.replyToId, 'review comment'),\n body: input.body,\n });\n return parseReviewComment(data);\n }\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 if ((input.startLine === undefined) !== (input.startSide === undefined)) {\n throw new Error('A multi-line review comment requires both startLine and startSide.');\n }\n const { data } = await octokit.pulls.createReviewComment({\n ...parts,\n pull_number: pullNumber,\n body: input.body,\n commit_id: input.commitId,\n path: input.path,\n line: input.line,\n side: input.side.toUpperCase() as 'LEFT' | 'RIGHT',\n start_line: input.startLine,\n start_side: input.startSide?.toUpperCase() as 'LEFT' | 'RIGHT' | undefined,\n });\n return parseReviewComment(data);\n }\n\n async #updateReviewComment(input: InputOf<'updateReviewComment'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.updateReviewComment({\n ...parts,\n comment_id: requirePositiveId(input.commentId, 'review comment'),\n body: input.body,\n });\n return parseReviewComment(data);\n }\n\n async #deleteReviewComment(input: InputOf<'deleteReviewComment'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n await octokit.pulls.deleteReviewComment({\n ...parts,\n comment_id: requirePositiveId(input.commentId, 'review comment'),\n });\n }\n\n async #listRequestedReviewers(input: InputOf<'listRequestedReviewers'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.listRequestedReviewers({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n });\n return parseRequestedReviewers(data);\n }\n\n async #requestReviewers(input: InputOf<'requestReviewers'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.requestReviewers({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n reviewers: input.users ?? [],\n team_reviewers: input.teams ?? [],\n });\n return parseRequestedReviewers(data);\n }\n\n async #removeReviewers(input: InputOf<'removeRequestedReviewers'>) {\n const { octokit, parts } = this.#repositoryClient(input.connection, input.sourceId);\n const { data } = await octokit.pulls.removeRequestedReviewers({\n ...parts,\n pull_number: requirePullRequestNumber(input.pullRequestId),\n reviewers: input.users ?? [],\n team_reviewers: input.teams ?? [],\n });\n return parseRequestedReviewers(data);\n }\n\n /** Add labels to an issue (deduplicated; no-op on empty/malformed input). */\n async addIssueLabels(\n installationId: number,\n repoFullName: string,\n issueNumber: number,\n labels: string[],\n ): Promise<void> {\n const parts = splitRepoFullName(repoFullName);\n if (!parts) return;\n const uniqueLabels = [...new Set(labels.map(label => label.trim()).filter(Boolean))];\n if (uniqueLabels.length === 0) return;\n const octokit = this.getInstallationOctokit(installationId);\n await octokit.issues.addLabels({\n owner: parts.owner,\n repo: parts.repo,\n issue_number: issueNumber,\n labels: uniqueLabels,\n });\n }\n\n /**\n * List one page of a repo's open issues through an installation token. The\n * issues API also returns pull requests, so those are filtered out (the\n * filter can make a non-final page shorter than the page size — `nextPage`\n * is derived from the raw response length, not the filtered one).\n */\n async listRepoOpenIssues(\n installationId: number,\n repoFullName: string,\n page: number,\n options: ListRepoOpenIssuesOptions = {},\n ): Promise<IssuePage> {\n const parts = splitRepoFullName(repoFullName);\n if (!parts) return { issues: [], nextPage: null };\n const octokit = this.getInstallationOctokit(installationId);\n const response = await octokit.issues.listForRepo({\n owner: parts.owner,\n repo: parts.repo,\n state: 'open',\n labels: options.label,\n per_page: LIST_PAGE_SIZE,\n page,\n });\n const issues = response.data\n .filter(issue => !issue.pull_request)\n .map(issue => ({\n number: issue.number,\n title: issue.title,\n url: issue.html_url,\n author: issue.user?.login ?? null,\n assignees: issue.assignees?.flatMap(assignee => (assignee.login ? [assignee.login] : [])) ?? [],\n labels: issue.labels.map(label => (typeof label === 'string' ? label : (label.name ?? ''))).filter(Boolean),\n comments: issue.comments,\n createdAt: issue.created_at,\n updatedAt: issue.updated_at,\n }));\n return { issues, nextPage: response.data.length === LIST_PAGE_SIZE ? page + 1 : null };\n }\n\n /**\n * Build the GitHub App install URL. `state` is carried through the install\n * flow and validated on callback.\n */\n buildInstallUrl(state: string): string {\n const url = new URL(`https://github.com/apps/${this.#slug}/installations/new`);\n url.searchParams.set('state', state);\n return url.toString();\n }\n\n /**\n * Build the OAuth identify URL (authorize) used to confirm the user's\n * identity and obtain a user token for listing their installations.\n */\n buildOAuthIdentifyUrl(state: string, redirectUri: string): string {\n const url = new URL('https://github.com/login/oauth/authorize');\n url.searchParams.set('client_id', this.#clientId);\n url.searchParams.set('redirect_uri', redirectUri);\n url.searchParams.set('state', state);\n return url.toString();\n }\n\n /** Exchange an OAuth `code` for a user access token. */\n async exchangeOAuthCode(code: string, redirectUri: string): Promise<string> {\n const res = await fetch('https://github.com/login/oauth/access_token', {\n method: 'POST',\n signal: AbortSignal.timeout(10_000),\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({\n client_id: this.#clientId,\n client_secret: this.#clientSecret,\n code,\n redirect_uri: redirectUri,\n }),\n });\n if (!res.ok) {\n throw new Error(`GitHub OAuth token exchange failed: ${res.status}`);\n }\n const data = (await res.json()) as { access_token?: string; error?: string; error_description?: string };\n if (!data.access_token) {\n throw new Error(\n `GitHub OAuth token exchange returned no token: ${data.error_description ?? data.error ?? 'unknown'}`,\n );\n }\n return data.access_token;\n }\n\n /**\n * The integration's HTTP surface: the `/web/github/*` + `/auth/github/*`\n * Mastra `apiRoutes` (webhook handler, install/OAuth flow, project +\n * worktree + session operations). The factory folds these into the server's\n * `apiRoutes` when the feature is ready. Handlers operate on this instance.\n */\n routes(ctx: IntegrationContext): ApiRoute[] {\n this.#storage = ctx.storage;\n const ingestFactoryEvent = attachGithubRules(this, ctx);\n return buildGithubRoutes({\n github: this,\n auth: ctx.auth,\n fleet: ctx.fleet,\n storage: ctx.factoryStorage,\n stateSigner: ctx.stateSigner,\n baseUrl: ctx.baseUrl,\n controller: ctx.controller,\n runIssueTriage: ctx.controller\n ? input => runGithubIssueTriage({ controller: ctx.controller!, input })\n : undefined,\n emitAudit: ctx.hooks?.emitAudit,\n projects: ctx.storage.projects,\n ingestFactoryEvent,\n });\n }\n\n /**\n * Merge-state safety net. Webhooks are the only other writer of merge state,\n * and a self-hosted deployment GitHub cannot reach (private network, local\n * dev) never receives one — without this sweep its PR cards stay open\n * forever. Disable with `MASTRACODE_GITHUB_RECONCILE_ENABLED=false`.\n */\n workers(ctx: IntegrationContext): MastraWorker[] {\n if (process.env.MASTRACODE_GITHUB_RECONCILE_ENABLED?.trim().toLowerCase() === 'false') return [];\n const reconcile = attachGithubReconciler(this, ctx, input => this.fetchPullRequestState(input));\n if (!reconcile) return [];\n const intervalMs = Number(process.env.MASTRACODE_GITHUB_RECONCILE_INTERVAL_MS);\n return [\n new GithubReconcileWorker({\n reconcile,\n sourceControl: ctx.storage.sourceControl,\n ...(Number.isSafeInteger(intervalMs) && intervalMs > 0 ? { intervalMs } : {}),\n }),\n ];\n }\n\n /**\n * Reads live PR state for the merge reconciler. Returns undefined when the PR\n * cannot be resolved 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 try {\n const pullRequest = await this.#getPullRequest({\n connection: { type: 'app-installation', installationId: input.installationId },\n sourceId: input.repository,\n pullRequestId: String(input.number),\n });\n if (!pullRequest) return undefined;\n return {\n title: pullRequest.title,\n url: pullRequest.url,\n state: pullRequest.state === 'closed' ? 'closed' : 'open',\n draft: pullRequest.draft,\n merged: pullRequest.merged,\n assignees: pullRequest.assignees ?? [],\n requestedReviewers: pullRequest.requestedReviewers ?? [],\n headBranch: pullRequest.headBranch,\n baseBranch: pullRequest.baseBranch,\n ...(pullRequest.author ? { author: pullRequest.author } : {}),\n ...(pullRequest.createdAt ? { createdAt: pullRequest.createdAt } : {}),\n };\n } catch {\n return undefined;\n }\n }\n\n /**\n * Session-scoped agent tools for token refresh and PR subscriptions in\n * sessions bound to a GitHub-backed project. Empty elsewhere.\n */\n sessionTools({ requestContext }: { requestContext: RequestContext }): IntegrationTools {\n return createGithubSubscriptionTools(requestContext, this);\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(requestContext, pullRequestUrl, 'auto-gh-pr-create', this);\n }\n\n /** Non-secret config snapshot for system diagnostics/startup logs. */\n diagnostics(): Record<string, unknown> {\n return {\n slug: this.#slug,\n webhookSecretConfigured: this.#webhookSecret !== undefined,\n };\n }\n}\n\ninterface GithubPullRequestData {\n number: number;\n title: string;\n html_url: string;\n user: { login?: string } | null;\n assignees?: Array<{ login?: string }> | null;\n requested_reviewers?: Array<{ login?: string }> | null;\n body?: string | null;\n state: string;\n draft?: boolean | null;\n merged?: boolean;\n merged_at?: string | null;\n mergeable?: boolean | null;\n base: { ref: string };\n head: { ref: string; sha: string };\n created_at: string;\n updated_at: string;\n}\n\ninterface GithubCommentData {\n id: number;\n html_url: string;\n user: { login?: string } | null;\n body?: string | null;\n created_at: string;\n updated_at: string;\n}\n\ninterface GithubReviewData {\n id: number;\n html_url?: string;\n user: { login?: string } | null;\n body?: string | null;\n state: string;\n commit_id?: string | null;\n submitted_at?: string | null;\n}\n\ninterface GithubReviewCommentData extends GithubCommentData {\n path: string;\n line?: number | null;\n side?: string | null;\n commit_id: string;\n in_reply_to_id?: number | null;\n}\n\nfunction parsePullRequest(pr: GithubPullRequestData): PullRequest {\n return {\n id: String(pr.number),\n title: pr.title,\n url: pr.html_url,\n author: pr.user?.login ?? null,\n assignees: (pr.assignees ?? []).flatMap(assignee => (assignee.login ? [assignee.login] : [])),\n requestedReviewers: (pr.requested_reviewers ?? []).flatMap(reviewer => (reviewer.login ? [reviewer.login] : [])),\n body: pr.body?.trim() ? pr.body : null,\n state: pr.state === 'closed' ? 'closed' : 'open',\n draft: pr.draft ?? false,\n merged: pr.merged ?? Boolean(pr.merged_at),\n mergeable: typeof pr.mergeable === 'boolean' ? pr.mergeable : null,\n baseBranch: pr.base.ref,\n headBranch: pr.head.ref,\n headSha: pr.head.sha,\n createdAt: pr.created_at,\n updatedAt: pr.updated_at,\n };\n}\n\nfunction parsePullRequestComment(comment: GithubCommentData): PullRequestComment {\n return {\n id: String(comment.id),\n url: comment.html_url,\n author: comment.user?.login ?? null,\n body: comment.body ?? '',\n createdAt: comment.created_at,\n updatedAt: comment.updated_at,\n };\n}\n\nfunction parseReview(review: GithubReviewData): Review {\n return {\n id: String(review.id),\n url: review.html_url ?? null,\n author: review.user?.login ?? null,\n body: review.body?.trim() ? review.body : null,\n state: parseReviewState(review.state),\n commitId: review.commit_id ?? null,\n submittedAt: review.submitted_at ?? null,\n };\n}\n\nfunction parseReviewComment(comment: GithubReviewCommentData): ReviewComment {\n const parsed = parsePullRequestComment(comment);\n const side = comment.side?.toLowerCase();\n return {\n ...parsed,\n path: comment.path,\n line: comment.line ?? null,\n side: side === 'left' || side === 'right' ? side : null,\n commitId: comment.commit_id,\n replyToId: comment.in_reply_to_id ? String(comment.in_reply_to_id) : null,\n };\n}\n\nfunction parseRequestedReviewers(data: {\n users?: Array<{ login?: string }> | null;\n teams?: Array<{ slug?: string }> | null;\n requested_reviewers?: Array<{ login?: string }> | null;\n requested_teams?: Array<{ slug?: string }> | null;\n}) {\n return {\n users: (data.users ?? data.requested_reviewers ?? []).flatMap(user => (user.login ? [user.login] : [])),\n teams: (data.teams ?? data.requested_teams ?? []).flatMap(team => (team.slug ? [team.slug] : [])),\n };\n}\n\nfunction parseReviewState(state: string): Review['state'] {\n if (state === 'PENDING') return 'pending';\n if (state === 'COMMENTED') return 'commented';\n if (state === 'APPROVED') return 'approved';\n if (state === 'CHANGES_REQUESTED') return 'changes-requested';\n if (state === 'DISMISSED') return 'dismissed';\n throw new Error(`Unsupported GitHub review state: ${state}`);\n}\n\nfunction reviewEventToGithub(event: Exclude<InputOf<'createReview'>['event'], undefined>) {\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 requirePullRequestNumber(value: string): number {\n return requirePositiveId(value, 'pull request');\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 getGithubInstallationId(connection: IntegrationConnection): number {\n if (connection.type !== 'app-installation') {\n throw new Error('GitHub capabilities require an app-installation connection.');\n }\n return connection.installationId;\n}\n\nfunction getSingleSourceId(sourceIds: string[], message: string): string {\n if (sourceIds.length !== 1) throw new Error(message);\n return sourceIds[0]!;\n}\n\nfunction normalizeLabels(labels: string[] | undefined): string[] {\n return [...new Set((labels ?? []).map(label => label.trim()).filter(Boolean))];\n}\n\nfunction requireSourceId(sourceId: string | undefined, message: string): string {\n if (!sourceId) throw new Error(message);\n return sourceId;\n}\n\nfunction parsePositiveCursor(cursor: string | undefined): number {\n if (cursor === undefined) return 1;\n const page = parsePositiveInteger(cursor);\n if (page === null) throw new Error('GitHub cursor must be a positive page number.');\n return page;\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 isNotFoundError(error: unknown): boolean {\n return typeof error === 'object' && error !== null && 'status' in error && error.status === 404;\n}\n\n/** Split an `owner/name` full name into its parts, or `null` when malformed. */\nfunction splitRepoFullName(repoFullName: string): { owner: string; repo: string } | null {\n const slash = repoFullName.indexOf('/');\n if (slash <= 0 || slash === repoFullName.length - 1) return null;\n return { owner: repoFullName.slice(0, slash), repo: repoFullName.slice(slash + 1) };\n}\n\nfunction parseGithubExternalTarget(externalId: string): { repositoryId: string; issueId: string } | null {\n const match = externalId.match(/^github:(\\d+):(?:issue|pull-request):(\\d+)$/) ?? externalId.match(/^(\\d+):(\\d+)$/);\n if (!match?.[1] || !match[2]) return null;\n const repositoryId = parsePositiveInteger(match[1]);\n const issueId = parsePositiveInteger(match[2]);\n return repositoryId && issueId ? { repositoryId: String(repositoryId), issueId: String(issueId) } : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyEA,SAAgB,oBAAoB,KAAqB;CACvD,MAAM,MAAM,IAAI,QAAQ,QAAQ,IAAI;CACpC,IAAI,IAAI,SAAS,IAAI,GAAG,OAAO;CAC/B,MAAM,YAAY,IAAI,KAAK,CAAC,CAAC,MAAM,qEAAqE;CACxG,IAAI,CAAC,WAAW,OAAO;CACvB,MAAM,OAAO,UAAU,EAAE,CAAE,QAAQ,QAAQ,EAAE;CAC7C,OAAO,GAAG,UAAU,GAAG,IAAI,KAAK,MAAM,UAAU,CAAC,CAAE,KAAK,IAAI,EAAE,IAAI,UAAU,GAAG;AACjF;;AAiCA,MAAa,iBAAiB;;AAmC9B,MAAM,kBAAkB;CAAC;CAAS;CAAc;CAAY;CAAgB;AAAM;AAElF,IAAa,oBAAb,MAA6D;;CAE3D,KAAc;CACd,SAA0B;EACxB,wBAAuB,UAAS,KAAKA,uBAAuB,KAAK;EACjE,aAAa,OAAO,EAAE,YAAY;GAChC,MAAM,gBAAgB,MAAM,KAAK,qBAAqB,cAAc,KAAK,EAAE,MAAM,CAAC;GAMlF,QAAO,MALoB,QAAQ,IACjC,cAAc,KAAI,iBAChB,KAAK,qBAAqB,aAAa,KAAK;IAAE;IAAO,gBAAgB,aAAa;GAAG,CAAC,CACxF,CACF,EAAA,CACoB,KA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,iBAAiB,CAAC;IAC3B;;;;OAIG;IACH,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,iFAAiF;IACjF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,4FAA4F;IAC5F,UAAU,CAAC,EAAE,iBAAiB,CAAC,YAAY,CAAC,CAAC;IAC7C,iEAAiE;IACjE,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,yBAAyB,KAAK,OAAO,CAAC,0BAA0B,CAAC,CAAC;IAC3F,6EAA6E;IAC7E,SAAS,CAAC,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;IACjC,2EAA2E;IAC3E,QAAQ,CAAC,EAAE,sBAAsB,CAAC;IAClC,+FAA+F;IAC/F,kBAAkB,CAAC,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CACvE;AA6OD;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,QAAQ,EAAE,CAkqB/E"}
|
|
@@ -2,7 +2,8 @@ import { clearGithubPat, getGithubPat, getGithubPatStatus, setGithubPat } from "
|
|
|
2
2
|
import { listPullRequestSubscriptionsForThread, subscribeToPullRequest } from "./subscriptions.js";
|
|
3
3
|
import { SandboxBudgetError } from "../../sandbox/fleet.js";
|
|
4
4
|
import { MaterializeError, WorktreeError, commitAll, computeWorktreePath, ensureProjectSandbox, isValidGitRef as isValidGitRef$1, materializeRepo, pushBranch, teardownProjectSandbox } from "./sandbox.js";
|
|
5
|
-
import {
|
|
5
|
+
import { reclaimDeletedSessionSandbox } from "./sandbox-release.js";
|
|
6
|
+
import { resolveFactoryDefaultModelId } from "../../session/factory-session.js";
|
|
6
7
|
import { getGithubFeatureDiagnostics, isGithubFeatureEnabled } from "./config.js";
|
|
7
8
|
import { handleGithubWebhook } from "./webhook.js";
|
|
8
9
|
import { registerApiRoute } from "@mastra/core/server";
|
|
@@ -41,19 +42,6 @@ function withSessionOperationLock(sessionId, fn) {
|
|
|
41
42
|
function loose(c) {
|
|
42
43
|
return c;
|
|
43
44
|
}
|
|
44
|
-
/**
|
|
45
|
-
* Resolve the Factory project's default model for a triage run. Best-effort:
|
|
46
|
-
* a missing project or an uninitialized storage domain simply means "no
|
|
47
|
-
* default", never a failed run.
|
|
48
|
-
*/
|
|
49
|
-
async function resolveFactoryDefaultModelId(projects, factoryProjectId) {
|
|
50
|
-
if (!projects || !factoryProjectId) return void 0;
|
|
51
|
-
try {
|
|
52
|
-
return (await projects.getById({ id: factoryProjectId }))?.defaultModelId ?? void 0;
|
|
53
|
-
} catch {
|
|
54
|
-
return;
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
45
|
function pullRequestNumberFromUrl(value, expectedRepo) {
|
|
58
46
|
try {
|
|
59
47
|
const url = new URL(value);
|
|
@@ -166,6 +154,7 @@ async function resolveProjectRepository(args) {
|
|
|
166
154
|
}
|
|
167
155
|
function polledIssueEvent(project, issue) {
|
|
168
156
|
const repositoryId = Number(project.repository.externalId);
|
|
157
|
+
const assigneeLogins = issue.assignees ?? (issue.assignee ? [issue.assignee] : []);
|
|
169
158
|
return {
|
|
170
159
|
event: "issues",
|
|
171
160
|
deliveryId: `poll:${repositoryId}:issue:${issue.number}:${issue.createdAt}`,
|
|
@@ -182,6 +171,7 @@ function polledIssueEvent(project, issue) {
|
|
|
182
171
|
title: issue.title,
|
|
183
172
|
html_url: issue.url,
|
|
184
173
|
created_at: issue.createdAt,
|
|
174
|
+
assignees: assigneeLogins.map((login) => ({ login })),
|
|
185
175
|
labels: issue.labels.map((name) => ({ name }))
|
|
186
176
|
}
|
|
187
177
|
}
|
|
@@ -207,6 +197,8 @@ function polledPullRequestEvent(project, pullRequest) {
|
|
|
207
197
|
created_at: pullRequest.createdAt,
|
|
208
198
|
state: "open",
|
|
209
199
|
merged: false,
|
|
200
|
+
assignees: pullRequest.assignees.map((login) => ({ login })),
|
|
201
|
+
requested_reviewers: pullRequest.requestedReviewers.map((login) => ({ login })),
|
|
210
202
|
head: { ref: pullRequest.headBranch },
|
|
211
203
|
base: { ref: pullRequest.baseBranch }
|
|
212
204
|
}
|
|
@@ -538,6 +530,8 @@ function buildGithubRoutes(options) {
|
|
|
538
530
|
title: issue.title,
|
|
539
531
|
url: issue.url,
|
|
540
532
|
author: issue.author,
|
|
533
|
+
assignee: issue.assignee,
|
|
534
|
+
assignees: issue.assignees,
|
|
541
535
|
labels: issue.labels,
|
|
542
536
|
comments: issue.commentCount ?? 0,
|
|
543
537
|
createdAt: issue.createdAt,
|
|
@@ -645,6 +639,8 @@ function buildGithubRoutes(options) {
|
|
|
645
639
|
title: pr.title,
|
|
646
640
|
url: pr.url,
|
|
647
641
|
author: pr.author,
|
|
642
|
+
assignees: pr.assignees ?? [],
|
|
643
|
+
requestedReviewers: pr.requestedReviewers ?? [],
|
|
648
644
|
baseBranch: pr.baseBranch,
|
|
649
645
|
headBranch: pr.headBranch,
|
|
650
646
|
createdAt: pr.createdAt,
|
|
@@ -1032,40 +1028,18 @@ function buildProjectGitRoutes({ github, auth, fleet, emitAudit }) {
|
|
|
1032
1028
|
if ("response" in resolved) return resolved.response;
|
|
1033
1029
|
const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
|
|
1034
1030
|
if (!session || session.orgId !== resolved.tenant.orgId || session.userId !== resolved.tenant.userId) return c.json({ error: "Session not found" }, 404);
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
});
|
|
1044
|
-
await github.sourceControlStorage.sandboxPool.release({
|
|
1045
|
-
orgId: session.orgId,
|
|
1046
|
-
projectRepositoryId: session.projectRepositoryId,
|
|
1047
|
-
userId: session.userId,
|
|
1031
|
+
await github.sourceControlStorage.sessions.delete(session.id);
|
|
1032
|
+
reclaimDeletedSessionSandbox({
|
|
1033
|
+
fleet,
|
|
1034
|
+
sourceControl: github.sourceControlStorage,
|
|
1035
|
+
session
|
|
1036
|
+
}).catch((error) => {
|
|
1037
|
+
console.error("[GitHub Sessions] Failed to reclaim sandbox for deleted session", {
|
|
1038
|
+
sessionId: session.sessionId,
|
|
1048
1039
|
sandboxId: session.sandboxId,
|
|
1049
|
-
|
|
1040
|
+
error
|
|
1050
1041
|
});
|
|
1051
|
-
}
|
|
1052
|
-
let sandbox;
|
|
1053
|
-
try {
|
|
1054
|
-
sandbox = await fleet.reattachSandbox(session.sandboxId);
|
|
1055
|
-
} catch {}
|
|
1056
|
-
await fleet.teardownSandbox({
|
|
1057
|
-
sandboxId: session.sandboxId,
|
|
1058
|
-
setSandboxId: async () => {},
|
|
1059
|
-
clear: async () => {
|
|
1060
|
-
await github.sourceControlStorage.sessions.setSandbox({
|
|
1061
|
-
id: session.id,
|
|
1062
|
-
sandboxId: null,
|
|
1063
|
-
sandboxWorkdir: session.sandboxWorkdir ?? ""
|
|
1064
|
-
});
|
|
1065
|
-
}
|
|
1066
|
-
}, sandbox);
|
|
1067
|
-
}
|
|
1068
|
-
await github.sourceControlStorage.sessions.delete(session.id);
|
|
1042
|
+
});
|
|
1069
1043
|
return c.json({ removed: true });
|
|
1070
1044
|
}
|
|
1071
1045
|
}),
|