@mastra/factory 0.17.3-alpha.2 → 0.17.3-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/integrations/github/issue-reconciler.d.ts +5 -3
- package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/github/issue-reconciler.js +24 -4
- package/dist/integrations/github/issue-reconciler.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +15 -0
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +14 -1
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/incidentio/integration.d.ts.map +1 -1
- package/dist/integrations/incidentio/integration.js +1 -0
- package/dist/integrations/incidentio/integration.js.map +1 -1
- package/dist/integrations/incidentio/routes.d.ts +5 -0
- package/dist/integrations/incidentio/routes.d.ts.map +1 -1
- package/dist/integrations/incidentio/routes.js +5 -1
- package/dist/integrations/incidentio/routes.js.map +1 -1
- package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
- package/dist/integrations/platform/connect/routes.js +4 -0
- package/dist/integrations/platform/connect/routes.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +15 -0
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +6 -0
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +26 -1
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
- package/dist/integrations/platform/incidentio/integration.js +1 -0
- package/dist/integrations/platform/incidentio/integration.js.map +1 -1
- package/package.json +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/incidentio/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the incident.io intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the host auth gate.\n * Mirrors the Jira module: no connect/callback flow here — credentials are\n * either deployment-global constructor config (direct) or Platform-managed\n * connections discovered at runtime. Every route re-resolves the\n * authenticated user from the request and scopes intake selections by the\n * caller's org.\n *\n * When the feature is disabled (no auth, or no intake storage),\n * `buildIncidentioRoutes` returns only `GET /web/incidentio/status`, which\n * reports `enabled:false` so the SPA can cleanly hide all incident.io UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport type { Intake } from '../../capabilities/intake.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport { IncidentioApiError } from './api.js';\nimport type { IncidentioRulesIngress } from './rules.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst ITEM_REF_RE = /^incidentio:(?:follow-up|incident):[\\w-]+$/;\nconst FOLLOW_UP_PREFIX = 'incidentio:follow-up:';\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\n\n/**\n * Non-secret diagnostic snapshot of every incident.io feature gate, mirroring\n * the Jira diagnostics shape. Only booleans — never values.\n */\nexport interface IncidentioFeatureDiagnostics {\n incidentioConfigured: boolean;\n factoryAuthEnabled: boolean;\n}\n\nexport interface MountIncidentioRoutesOptions {\n /**\n * The integration's intake capability providing incident.io access. Required\n * for everything beyond the disabled `status` route.\n */\n incidentio?: { intake: Intake; id: string };\n /** Host auth seam. Intake selections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Cross-integration intake selection domain. Required for the issues route's\n * project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\n /**\n * Factory rules ingress for observed follow-ups. When present, a\n * board-scoped listing also materializes new cards through the incident.io\n * event rules — the same automatic intake Linear and Jira have.\n */\n ingestFactoryIssues?: (input: IncidentioRulesIngress) => Promise<unknown>;\n}\n\n/**\n * Narrow the caller's selected incident.io sources to the ones that feed this\n * Factory project. Routing is explicit: a source feeds this Factory only when\n * its binding names both the Factory project and a board. Mirrors the Jira\n * routes' scoping semantics — the generic binding storage is provider-neutral.\n * Shared with the agent tools, which enforce the same source-level\n * authorization before fetching item details.\n */\nexport async function scopeSourceIdsToProject({\n intake,\n orgId,\n factoryProjectId,\n selectedIds,\n}: {\n intake: IntakeStorage;\n orgId: string;\n factoryProjectId: string;\n selectedIds: string[];\n}): Promise<Record<string, string>> {\n const selected = new Set(selectedIds);\n const intakeBoards: Record<string, string> = {};\n for (const binding of await intake.listBindings({ orgId, integrationId: 'incidentio' })) {\n if (binding.factoryProjectId === factoryProjectId && binding.board && selected.has(binding.sourceId)) {\n intakeBoards[binding.sourceId] = binding.board;\n }\n }\n return intakeBoards;\n}\n\n/**\n * Resolve the org-scoped tenant for an incident.io request. Intake selections\n * are org-owned, so it requires both a signed-in user and an organization.\n */\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'incident.io intake requires an organization. Personal accounts cannot use incident.io intake.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque pagination cursor from the query string. Cursors are\n * server-issued base64url blobs, so anything outside a conservative\n * charset/length is rejected rather than decoded.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 2_048 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map an incident.io read failure to the API response for the SPA. */\nfunction incidentioFetchError(c: RouteContext, err: unknown) {\n if (err instanceof IncidentioApiError && (err.status === 401 || err.status === 403)) {\n return c.json(\n {\n error: 'incidentio_auth_failed',\n message: 'incident.io rejected the configured credentials. Reconnect the incident.io account.',\n },\n 409,\n );\n }\n return c.json({ error: 'incidentio_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\ninterface IncidentioIssuePayload {\n id: string;\n identifier: string;\n title: string;\n url: string;\n author: string | null;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n incident: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n sourceId: string | null;\n}\n\n/**\n * Build the incident.io routes as Mastra `apiRoutes`. When the feature is\n * disabled, returns only the `status` route so the SPA can detect the\n * disabled state.\n */\nexport function buildIncidentioRoutes(options: MountIncidentioRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { incidentio, auth, intake } = options;\n const enabled = Boolean(incidentio) && auth.enabled();\n const diagnostics = (): IncidentioFeatureDiagnostics => ({\n incidentioConfigured: Boolean(incidentio),\n factoryAuthEnabled: auth.enabled(),\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/incidentio/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !incidentio || !intake) {\n return c.json({\n enabled: false,\n configured: Boolean(incidentio),\n reason: 'missing_config',\n diagnostics: diagnostics(),\n });\n }\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: true,\n organizationRequired: true,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n return c.json({ enabled: true, configured: true, reason: 'ready', diagnostics: diagnostics() });\n },\n }),\n );\n\n // Without the integration instance or the intake domain the feature can't\n // serve org-scoped data — serve only the disabled `status` route.\n if (!enabled || !incidentio || !intake) {\n return routes;\n }\n\n // ── List bound follow-ups (cursor-paged) ────────────────────────────────\n // Respects the caller's intake config: disabled incident.io intake 404s,\n // and only sources routed to the requested Factory project are listed.\n // Incidents never appear here — only follow-ups feed intake.\n routes.push(\n registerApiRoute('/web/incidentio/issues', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const after = parseAfterCursor(c.req.query('after'));\n if (after === null) return c.json({ error: 'invalid_cursor' }, 400);\n const factoryProjectId = c.req.query('factoryProjectId');\n if (factoryProjectId && !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['incidentio'] });\n const selection = config.incidentio!;\n if (!selection.enabled) {\n return c.json(\n { error: 'incidentio_intake_disabled', message: 'incident.io intake is turned off in Settings.' },\n 404,\n );\n }\n\n const selectedIds = selection.sourceIds ?? [];\n const intakeBoards = factoryProjectId\n ? await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const sourceIds = intakeBoards ? Object.keys(intakeBoards) : selectedIds;\n if (sourceIds.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const page = await incidentio.intake.listItems({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n sourceIds,\n ...(after ? { cursor: after } : {}),\n });\n const issuePayload: IncidentioIssuePayload[] = [];\n for (const item of page.items) {\n const externalId = item.source.externalId;\n // Incidents stay out of intake even when a stale binding selects\n // the incidents source — only follow-ups are served.\n if (!externalId.startsWith(FOLLOW_UP_PREFIX)) continue;\n const metadata = item.metadata ?? {};\n const identifier = typeof metadata.identifier === 'string' ? metadata.identifier : externalId;\n const titlePrefix = `${identifier}: `;\n issuePayload.push({\n id: externalId,\n identifier,\n title: item.title.startsWith(titlePrefix) ? item.title.slice(titlePrefix.length) : item.title,\n url: item.source.url ?? '',\n author: typeof metadata.author === 'string' ? metadata.author : null,\n state: item.status ?? '',\n stateType: typeof metadata.stateType === 'string' ? metadata.stateType : '',\n priorityLabel: typeof metadata.priority === 'string' ? metadata.priority : '',\n assignee: item.assignee ?? null,\n incident: typeof metadata.incidentioIncidentId === 'string' ? metadata.incidentioIncidentId : null,\n labels: item.labels ?? [],\n createdAt: item.createdAt ?? '',\n updatedAt: item.updatedAt ?? '',\n sourceId: item.sourceId || null,\n });\n }\n if (factoryProjectId && intakeBoards && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n intakeBoards,\n });\n }\n return c.json({ issues: issuePayload, nextCursor: page.nextCursor });\n } catch (err) {\n return incidentioFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── Follow-up detail (description for the card panel) ───────────────────\n routes.push(\n registerApiRoute('/web/incidentio/issues/detail', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const factoryProjectId = c.req.query('factoryProjectId');\n const issueRef = c.req.query('issueRef');\n if (!factoryProjectId || !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n if (!issueRef || issueRef.length > 2_048 || !ITEM_REF_RE.test(issueRef)) {\n return c.json({ error: 'invalid_issue_ref' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['incidentio'] });\n const selection = config.incidentio!;\n if (!selection.enabled) {\n return c.json(\n { error: 'incidentio_intake_disabled', message: 'incident.io intake is turned off in Settings.' },\n 404,\n );\n }\n const intakeBoards = await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n if (Object.keys(intakeBoards).length === 0) return c.json({ error: 'issue_not_found' }, 404);\n\n try {\n // The item must resolve through a source routed to this Factory —\n // an item from an unbound source reads exactly like one that\n // doesn't exist (same stance as the Jira detail route).\n const dispatch = await incidentio.intake.resolveIntakeDispatch?.({\n orgId: resolved.tenant.orgId,\n externalSource: { type: 'issue', externalId: issueRef },\n });\n if (!dispatch || !dispatch.sourceId || !(dispatch.sourceId in intakeBoards)) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n const issue = await incidentio.intake.getIssue({\n connection: dispatch.connection,\n issueId: dispatch.issueId,\n });\n if (!issue) return c.json({ error: 'issue_not_found' }, 404);\n return c.json({\n issue: {\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n description: issue.description ?? null,\n },\n });\n } catch (err) {\n return incidentioFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n"],"mappings":";;;AA2BA,MAAM,UAAU;AAChB,MAAM,cAAc;AACpB,MAAM,mBAAmB;;AAGzB,SAAS,MAAM,GAA0B;CACvC,OAAO;AACT;;;;;;;;;AAwCA,eAAsB,wBAAwB,EAC5C,QACA,OACA,kBACA,eAMkC;CAClC,MAAM,WAAW,IAAI,IAAI,WAAW;CACpC,MAAM,eAAuC,CAAC;CAC9C,KAAK,MAAM,WAAW,MAAM,OAAO,aAAa;EAAE;EAAO,eAAe;CAAa,CAAC,GACpF,IAAI,QAAQ,qBAAqB,oBAAoB,QAAQ,SAAS,SAAS,IAAI,QAAQ,QAAQ,GACjG,aAAa,QAAQ,YAAY,QAAQ;CAG7C,OAAO;AACT;;;;;AAMA,eAAe,iBACb,GACA,MACiF;CACjF,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;CACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KACV;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF,EACF;C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,SAAS;KACrB,SAAS,SAAS;IACpB,CAAC;IACD,IAAI,CAAC,OAAO,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;IAC3D,OAAO,EAAE,KAAK,EACZ,OAAO;KACL,YAAY,MAAM;KAClB,OAAO,MAAM;KACb,KAAK,MAAM;KACX,aAAa,MAAM,eAAe;IACpC,EACF,CAAC;GACH,SAAS,KAAK;IACZ,OAAO,qBAAqB,MAAM,CAAC,GAAG,GAAG;GAC3C;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/incidentio/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the incident.io intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the host auth gate.\n * Mirrors the Jira module: no connect/callback flow here — credentials are\n * either deployment-global constructor config (direct) or Platform-managed\n * connections discovered at runtime. Every route re-resolves the\n * authenticated user from the request and scopes intake selections by the\n * caller's org.\n *\n * When the feature is disabled (no auth, or no intake storage),\n * `buildIncidentioRoutes` returns only `GET /web/incidentio/status`, which\n * reports `enabled:false` so the SPA can cleanly hide all incident.io UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport type { Intake } from '../../capabilities/intake.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport { IncidentioApiError } from './api.js';\nimport type { IncidentioRulesIngress } from './rules.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst ITEM_REF_RE = /^incidentio:(?:follow-up|incident):[\\w-]+$/;\nconst FOLLOW_UP_PREFIX = 'incidentio:follow-up:';\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\n\n/**\n * Non-secret diagnostic snapshot of every incident.io feature gate, mirroring\n * the Jira diagnostics shape. Only booleans — never values.\n */\nexport interface IncidentioFeatureDiagnostics {\n incidentioConfigured: boolean;\n factoryAuthEnabled: boolean;\n}\n\nexport interface MountIncidentioRoutesOptions {\n /**\n * The integration's intake capability providing incident.io access. Required\n * for everything beyond the disabled `status` route.\n */\n incidentio?: { intake: Intake; id: string };\n /**\n * Credential mode reported on the status route so the SPA can tell a\n * deployment-configured API key apart from Platform-managed connections.\n */\n mode?: 'api-key' | 'platform';\n /** Host auth seam. Intake selections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Cross-integration intake selection domain. Required for the issues route's\n * project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\n /**\n * Factory rules ingress for observed follow-ups. When present, a\n * board-scoped listing also materializes new cards through the incident.io\n * event rules — the same automatic intake Linear and Jira have.\n */\n ingestFactoryIssues?: (input: IncidentioRulesIngress) => Promise<unknown>;\n}\n\n/**\n * Narrow the caller's selected incident.io sources to the ones that feed this\n * Factory project. Routing is explicit: a source feeds this Factory only when\n * its binding names both the Factory project and a board. Mirrors the Jira\n * routes' scoping semantics — the generic binding storage is provider-neutral.\n * Shared with the agent tools, which enforce the same source-level\n * authorization before fetching item details.\n */\nexport async function scopeSourceIdsToProject({\n intake,\n orgId,\n factoryProjectId,\n selectedIds,\n}: {\n intake: IntakeStorage;\n orgId: string;\n factoryProjectId: string;\n selectedIds: string[];\n}): Promise<Record<string, string>> {\n const selected = new Set(selectedIds);\n const intakeBoards: Record<string, string> = {};\n for (const binding of await intake.listBindings({ orgId, integrationId: 'incidentio' })) {\n if (binding.factoryProjectId === factoryProjectId && binding.board && selected.has(binding.sourceId)) {\n intakeBoards[binding.sourceId] = binding.board;\n }\n }\n return intakeBoards;\n}\n\n/**\n * Resolve the org-scoped tenant for an incident.io request. Intake selections\n * are org-owned, so it requires both a signed-in user and an organization.\n */\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'incident.io intake requires an organization. Personal accounts cannot use incident.io intake.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque pagination cursor from the query string. Cursors are\n * server-issued base64url blobs, so anything outside a conservative\n * charset/length is rejected rather than decoded.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 2_048 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map an incident.io read failure to the API response for the SPA. */\nfunction incidentioFetchError(c: RouteContext, err: unknown) {\n if (err instanceof IncidentioApiError && (err.status === 401 || err.status === 403)) {\n return c.json(\n {\n error: 'incidentio_auth_failed',\n message: 'incident.io rejected the configured credentials. Reconnect the incident.io account.',\n },\n 409,\n );\n }\n return c.json({ error: 'incidentio_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\ninterface IncidentioIssuePayload {\n id: string;\n identifier: string;\n title: string;\n url: string;\n author: string | null;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n incident: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n sourceId: string | null;\n}\n\n/**\n * Build the incident.io routes as Mastra `apiRoutes`. When the feature is\n * disabled, returns only the `status` route so the SPA can detect the\n * disabled state.\n */\nexport function buildIncidentioRoutes(options: MountIncidentioRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { incidentio, auth, intake, mode } = options;\n const enabled = Boolean(incidentio) && auth.enabled();\n const modeField = mode ? { mode } : {};\n const diagnostics = (): IncidentioFeatureDiagnostics => ({\n incidentioConfigured: Boolean(incidentio),\n factoryAuthEnabled: auth.enabled(),\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/incidentio/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !incidentio || !intake) {\n return c.json({\n enabled: false,\n configured: Boolean(incidentio),\n ...modeField,\n reason: 'missing_config',\n diagnostics: diagnostics(),\n });\n }\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: true,\n ...modeField,\n organizationRequired: true,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n return c.json({ enabled: true, configured: true, ...modeField, reason: 'ready', diagnostics: diagnostics() });\n },\n }),\n );\n\n // Without the integration instance or the intake domain the feature can't\n // serve org-scoped data — serve only the disabled `status` route.\n if (!enabled || !incidentio || !intake) {\n return routes;\n }\n\n // ── List bound follow-ups (cursor-paged) ────────────────────────────────\n // Respects the caller's intake config: disabled incident.io intake 404s,\n // and only sources routed to the requested Factory project are listed.\n // Incidents never appear here — only follow-ups feed intake.\n routes.push(\n registerApiRoute('/web/incidentio/issues', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const after = parseAfterCursor(c.req.query('after'));\n if (after === null) return c.json({ error: 'invalid_cursor' }, 400);\n const factoryProjectId = c.req.query('factoryProjectId');\n if (factoryProjectId && !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['incidentio'] });\n const selection = config.incidentio!;\n if (!selection.enabled) {\n return c.json(\n { error: 'incidentio_intake_disabled', message: 'incident.io intake is turned off in Settings.' },\n 404,\n );\n }\n\n const selectedIds = selection.sourceIds ?? [];\n const intakeBoards = factoryProjectId\n ? await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const sourceIds = intakeBoards ? Object.keys(intakeBoards) : selectedIds;\n if (sourceIds.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const page = await incidentio.intake.listItems({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n sourceIds,\n ...(after ? { cursor: after } : {}),\n });\n const issuePayload: IncidentioIssuePayload[] = [];\n for (const item of page.items) {\n const externalId = item.source.externalId;\n // Incidents stay out of intake even when a stale binding selects\n // the incidents source — only follow-ups are served.\n if (!externalId.startsWith(FOLLOW_UP_PREFIX)) continue;\n const metadata = item.metadata ?? {};\n const identifier = typeof metadata.identifier === 'string' ? metadata.identifier : externalId;\n const titlePrefix = `${identifier}: `;\n issuePayload.push({\n id: externalId,\n identifier,\n title: item.title.startsWith(titlePrefix) ? item.title.slice(titlePrefix.length) : item.title,\n url: item.source.url ?? '',\n author: typeof metadata.author === 'string' ? metadata.author : null,\n state: item.status ?? '',\n stateType: typeof metadata.stateType === 'string' ? metadata.stateType : '',\n priorityLabel: typeof metadata.priority === 'string' ? metadata.priority : '',\n assignee: item.assignee ?? null,\n incident: typeof metadata.incidentioIncidentId === 'string' ? metadata.incidentioIncidentId : null,\n labels: item.labels ?? [],\n createdAt: item.createdAt ?? '',\n updatedAt: item.updatedAt ?? '',\n sourceId: item.sourceId || null,\n });\n }\n if (factoryProjectId && intakeBoards && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n intakeBoards,\n });\n }\n return c.json({ issues: issuePayload, nextCursor: page.nextCursor });\n } catch (err) {\n return incidentioFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── Follow-up detail (description for the card panel) ───────────────────\n routes.push(\n registerApiRoute('/web/incidentio/issues/detail', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const factoryProjectId = c.req.query('factoryProjectId');\n const issueRef = c.req.query('issueRef');\n if (!factoryProjectId || !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n if (!issueRef || issueRef.length > 2_048 || !ITEM_REF_RE.test(issueRef)) {\n return c.json({ error: 'invalid_issue_ref' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['incidentio'] });\n const selection = config.incidentio!;\n if (!selection.enabled) {\n return c.json(\n { error: 'incidentio_intake_disabled', message: 'incident.io intake is turned off in Settings.' },\n 404,\n );\n }\n const intakeBoards = await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n if (Object.keys(intakeBoards).length === 0) return c.json({ error: 'issue_not_found' }, 404);\n\n try {\n // The item must resolve through a source routed to this Factory —\n // an item from an unbound source reads exactly like one that\n // doesn't exist (same stance as the Jira detail route).\n const dispatch = await incidentio.intake.resolveIntakeDispatch?.({\n orgId: resolved.tenant.orgId,\n externalSource: { type: 'issue', externalId: issueRef },\n });\n if (!dispatch || !dispatch.sourceId || !(dispatch.sourceId in intakeBoards)) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n const issue = await incidentio.intake.getIssue({\n connection: dispatch.connection,\n issueId: dispatch.issueId,\n });\n if (!issue) return c.json({ error: 'issue_not_found' }, 404);\n return c.json({\n issue: {\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n description: issue.description ?? null,\n },\n });\n } catch (err) {\n return incidentioFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n"],"mappings":";;;AA2BA,MAAM,UAAU;AAChB,MAAM,cAAc;AACpB,MAAM,mBAAmB;;AAGzB,SAAS,MAAM,GAA0B;CACvC,OAAO;A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AY,MADG,OAAO,UAAU;IAAE,OAAO,SAAS,OAAO;IAAO,gBAAgB,CAAC,YAAY;GAAE,CAAC,EAAA,CAC7E;GACzB,IAAI,CAAC,UAAU,SACb,OAAO,EAAE,KACP;IAAE,OAAO;IAA8B,SAAS;GAAgD,GAChG,GACF;GAEF,MAAM,eAAe,MAAM,wBAAwB;IACjD;IACA,OAAO,SAAS,OAAO;IACvB;IACA,aAAa,UAAU,aAAa,CAAC;GACvC,CAAC;GACD,IAAI,OAAO,KAAK,YAAY,CAAC,CAAC,WAAW,GAAG,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;GAE3F,IAAI;IAIF,MAAM,WAAW,MAAM,WAAW,OAAO,wBAAwB;KAC/D,OAAO,SAAS,OAAO;KACvB,gBAAgB;MAAE,MAAM;MAAS,YAAY;KAAS;IACxD,CAAC;IACD,IAAI,CAAC,YAAY,CAAC,SAAS,YAAY,EAAE,SAAS,YAAY,eAC5D,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;IAEjD,MAAM,QAAQ,MAAM,WAAW,OAAO,SAAS;KAC7C,YAAY,SAAS;KACrB,SAAS,SAAS;IACpB,CAAC;IACD,IAAI,CAAC,OAAO,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;IAC3D,OAAO,EAAE,KAAK,EACZ,OAAO;KACL,YAAY,MAAM;KAClB,OAAO,MAAM;KACb,KAAK,MAAM;KACX,aAAa,MAAM,eAAe;IACpC,EACF,CAAC;GACH,SAAS,KAAK;IACZ,OAAO,qBAAqB,MAAM,CAAC,GAAG,GAAG;GAC3C;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/connect/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAIpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAoB,MAAM,kBAAkB,CAAC;AASvE,MAAM,WAAW,uBAAuB;IACtC,6DAA6D;IAC7D,aAAa,EAAE,MAAM,CAAC;IACtB,wEAAwE;IACxE,wBAAwB,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C;AAED;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,EAAE,MAAM,CAAC,MAAM,EAAE,uBAAuB,
|
|
1
|
+
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/connect/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAIpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAoB,MAAM,kBAAkB,CAAC;AASvE,MAAM,WAAW,uBAAuB;IACtC,6DAA6D;IAC7D,aAAa,EAAE,MAAM,CAAC;IACtB,wEAAwE;IACxE,wBAAwB,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C;AAED;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,EAAE,MAAM,CAAC,MAAM,EAAE,uBAAuB,CAI9E,CAAC;AAmBF,MAAM,WAAW,iCAAiC;IAChD,IAAI,EAAE,SAAS,CAAC;IAChB,MAAM,EAAE,iBAAiB,CAAC;CAC3B;AA2CD;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,iCAAiC,GAAG,QAAQ,EAAE,CAgFjG"}
|
|
@@ -19,6 +19,10 @@ const PLATFORM_CONNECT_PROVIDERS = {
|
|
|
19
19
|
"incident-io": {
|
|
20
20
|
integrationId: "incident-io",
|
|
21
21
|
connectionIntegrationIds: ["incident-io"]
|
|
22
|
+
},
|
|
23
|
+
gitlab: {
|
|
24
|
+
integrationId: "gitlab",
|
|
25
|
+
connectionIntegrationIds: ["gitlab"]
|
|
22
26
|
}
|
|
23
27
|
};
|
|
24
28
|
async function resolveOrgTenant(c, auth) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/connect/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` that let the Factory SPA connect and reconnect\n * Platform-managed provider accounts without leaving Factory.\n *\n * The browser cannot talk to the integrations service itself — it has no\n * Platform session — so these routes mint Nango connect/reconnect sessions\n * server-side with the deploy's machine credentials\n * (`MASTRA_PLATFORM_ACCESS_TOKEN`/`MASTRA_PLATFORM_SECRET_KEY`) and hand the\n * short-lived session token back to the SPA, which drives the provider's\n * OAuth popup headlessly via `@nangohq/frontend`. Gating mirrors the\n * Platform's own rule for these providers: a signed-in organization member\n * (org:write parity with Linear), not an organization admin.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport type { RouteAuth } from '../../../routes/route.js';\nimport { PlatformApiClient, PlatformApiError } from '../api-client.js';\n\ntype RouteContext = Context;\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\n\nexport interface PlatformConnectProvider {\n /** Platform integration id used to mint connect sessions. */\n integrationId: string;\n /** Connection `integrationId` variants that belong to this provider. */\n connectionIntegrationIds: readonly string[];\n}\n\n/**\n * Providers the Factory SPA may connect through these routes. Keys are the\n * SPA-facing provider slugs; `integrationId` is the Platform catalog id used\n * for new connect sessions. Provider-specific PRs extend this registry when\n * their Factory integrations are available.\n */\nexport const PLATFORM_CONNECT_PROVIDERS: Record<string, PlatformConnectProvider> = {\n jira: { integrationId: 'jira', connectionIntegrationIds: ['jira'] },\n 'incident-io': { integrationId: 'incident-io', connectionIntegrationIds: ['incident-io'] },\n};\n\ninterface PlatformConnectionRow {\n id: string;\n integrationId: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n displayName?: string | null;\n connectedAt?: string;\n}\n\ninterface PlatformSessionResponse {\n connectionId: string;\n integrationId: string;\n connectUrl: string;\n sessionToken: string;\n expiresAt: string;\n}\n\nexport interface BuildPlatformConnectRoutesOptions {\n auth: RouteAuth;\n client: PlatformApiClient;\n}\n\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n if (!auth.enabled()) {\n return { response: c.json({ error: 'auth_disabled', message: 'Factory auth is not enabled.' }, 403) };\n }\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Provider connections require an organization. Personal accounts cannot connect providers.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\nfunction providerFromParam(c: RouteContext): PlatformConnectProvider | null {\n const provider = c.req.param('provider');\n return provider ? (PLATFORM_CONNECT_PROVIDERS[provider] ?? null) : null;\n}\n\nfunction platformError(c: RouteContext, err: unknown) {\n if (err instanceof PlatformApiError) {\n if (err.status === 409) {\n return c.json({ error: 'session_pending', message: err.message }, 409);\n }\n if (err.status === 403) {\n return c.json({ error: 'platform_forbidden', message: err.message }, 403);\n }\n }\n return c.json({ error: 'platform_request_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the `/web/integrations/platform/*` routes. Callers only mount these\n * when Platform machine credentials are configured.\n */\nexport function buildPlatformConnectRoutes(options: BuildPlatformConnectRoutesOptions): ApiRoute[] {\n const { auth, client } = options;\n\n return [\n registerApiRoute('/web/integrations/platform/:provider/connections', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const result = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connections = result.connections.filter(connection =>\n provider.connectionIntegrationIds.includes(connection.integrationId),\n );\n return c.json({ connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/integrations/${encodeURIComponent(provider.integrationId)}/connect-sessions`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connections/:connectionId/reconnect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n const connectionId = c.req.param('connectionId');\n if (!connectionId) return c.json({ error: 'connection_required' }, 400);\n try {\n // Confirm the connection belongs to this provider before minting so\n // one provider's page cannot reconnect a different provider's\n // connection through this route family.\n const listed = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connection = listed.connections.find(\n candidate =>\n candidate.id === connectionId && provider.connectionIntegrationIds.includes(candidate.integrationId),\n );\n if (!connection) return c.json({ error: 'connection_not_found' }, 404);\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/connections/${encodeURIComponent(connectionId)}/reconnect-session`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n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AAW,kBAAkB,CAAC;IACpC,IAAI,CAAC,UAAU,OAAO,EAAE,KAAK,EAAE,OAAO,mBAAmB,GAAG,GAAG;IAC/D,MAAM,WAAW,MAAM,iBAAiB,GAAG,IAAI;IAC/C,IAAI,cAAc,UAAU,OAAO,SAAS;IAC5C,MAAM,eAAe,EAAE,IAAI,MAAM,cAAc;IAC/C,IAAI,CAAC,cAAc,OAAO,EAAE,KAAK,EAAE,OAAO,sBAAsB,GAAG,GAAG;IACtE,IAAI;KASF,IAAI,EAJe,MADE,OAAO,QAAkD,OAAO,iBAAiB,EAAA,CAC5E,YAAY,MACpC,cACE,UAAU,OAAO,gBAAgB,SAAS,yBAAyB,SAAS,UAAU,aAAa,CAEzF,GAAG,OAAO,EAAE,KAAK,EAAE,OAAO,uBAAuB,GAAG,GAAG;KACrE,MAAM,UAAU,MAAM,OAAO,QAC3B,QACA,mBAAmB,mBAAmB,YAAY,EAAE,qBACpD,CAAC,CACH;KACA,EAAE,OAAO,iBAAiB,UAAU;KACpC,OAAO,EAAE,KAAK,SAAS,GAAG;IAC5B,SAAS,KAAK;KACZ,OAAO,cAAc,GAAG,GAAG;IAC7B;GACF;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/connect/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` that let the Factory SPA connect and reconnect\n * Platform-managed provider accounts without leaving Factory.\n *\n * The browser cannot talk to the integrations service itself — it has no\n * Platform session — so these routes mint Nango connect/reconnect sessions\n * server-side with the deploy's machine credentials\n * (`MASTRA_PLATFORM_ACCESS_TOKEN`/`MASTRA_PLATFORM_SECRET_KEY`) and hand the\n * short-lived session token back to the SPA, which drives the provider's\n * OAuth popup headlessly via `@nangohq/frontend`. Gating mirrors the\n * Platform's own rule for these providers: a signed-in organization member\n * (org:write parity with Linear), not an organization admin.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport type { RouteAuth } from '../../../routes/route.js';\nimport { PlatformApiClient, PlatformApiError } from '../api-client.js';\n\ntype RouteContext = Context;\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\n\nexport interface PlatformConnectProvider {\n /** Platform integration id used to mint connect sessions. */\n integrationId: string;\n /** Connection `integrationId` variants that belong to this provider. */\n connectionIntegrationIds: readonly string[];\n}\n\n/**\n * Providers the Factory SPA may connect through these routes. Keys are the\n * SPA-facing provider slugs; `integrationId` is the Platform catalog id used\n * for new connect sessions. Provider-specific PRs extend this registry when\n * their Factory integrations are available.\n */\nexport const PLATFORM_CONNECT_PROVIDERS: Record<string, PlatformConnectProvider> = {\n jira: { integrationId: 'jira', connectionIntegrationIds: ['jira'] },\n 'incident-io': { integrationId: 'incident-io', connectionIntegrationIds: ['incident-io'] },\n gitlab: { integrationId: 'gitlab', connectionIntegrationIds: ['gitlab'] },\n};\n\ninterface PlatformConnectionRow {\n id: string;\n integrationId: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n displayName?: string | null;\n connectedAt?: string;\n}\n\ninterface PlatformSessionResponse {\n connectionId: string;\n integrationId: string;\n connectUrl: string;\n sessionToken: string;\n expiresAt: string;\n}\n\nexport interface BuildPlatformConnectRoutesOptions {\n auth: RouteAuth;\n client: PlatformApiClient;\n}\n\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n if (!auth.enabled()) {\n return { response: c.json({ error: 'auth_disabled', message: 'Factory auth is not enabled.' }, 403) };\n }\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Provider connections require an organization. Personal accounts cannot connect providers.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\nfunction providerFromParam(c: RouteContext): PlatformConnectProvider | null {\n const provider = c.req.param('provider');\n return provider ? (PLATFORM_CONNECT_PROVIDERS[provider] ?? null) : null;\n}\n\nfunction platformError(c: RouteContext, err: unknown) {\n if (err instanceof PlatformApiError) {\n if (err.status === 409) {\n return c.json({ error: 'session_pending', message: err.message }, 409);\n }\n if (err.status === 403) {\n return c.json({ error: 'platform_forbidden', message: err.message }, 403);\n }\n }\n return c.json({ error: 'platform_request_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the `/web/integrations/platform/*` routes. Callers only mount these\n * when Platform machine credentials are configured.\n */\nexport function buildPlatformConnectRoutes(options: BuildPlatformConnectRoutesOptions): ApiRoute[] {\n const { auth, client } = options;\n\n return [\n registerApiRoute('/web/integrations/platform/:provider/connections', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const result = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connections = result.connections.filter(connection =>\n provider.connectionIntegrationIds.includes(connection.integrationId),\n );\n return c.json({ connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/integrations/${encodeURIComponent(provider.integrationId)}/connect-sessions`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connections/:connectionId/reconnect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n const connectionId = c.req.param('connectionId');\n if (!connectionId) return c.json({ error: 'connection_required' }, 400);\n try {\n // Confirm the connection belongs to this provider before minting so\n // one provider's page cannot reconnect a different provider's\n // connection through this route family.\n const listed = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connection = listed.connections.find(\n candidate =>\n candidate.id === connectionId && provider.connectionIntegrationIds.includes(candidate.integrationId),\n );\n if (!connection) return c.json({ error: 'connection_not_found' }, 404);\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/connections/${encodeURIComponent(connectionId)}/reconnect-session`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n ];\n}\n"],"mappings":";;;;AAwBA,SAAS,MAAM,GAA0B;CACvC,OAAO;AACT;;;;;;;AAeA,MAAa,6BAAsE;CACjF,MAAM;EAAE,eAAe;EAAQ,0BAA0B,CAAC,MAAM;CAAE;CAClE,eAAe;EAAE,eAAe;EAAe,0BAA0B,CAAC,aAAa;CAAE;CACzF,QAAQ;EAAE,eAAe;EAAU,0BAA0B,CAAC,QAAQ;CAAE;AAC1E;AAwBA,eAAe,iBACb,GACA,MACiF;CACjF,IAAI,CAAC,KAAK,QAAQ,GAChB,OAAO,EAAE,UAAU,EAAE,KAAK;EAAE,OAAO;EAAiB,SAAS;CAA+B,GAAG,GAAG,EAAE;CAEtG,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;CACvE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O,QAC3B,QACA,mBAAmB,mBAAmB,YAAY,EAAE,qBACpD,CAAC,CACH;KACA,EAAE,OAAO,iBAAiB,UAAU;KACpC,OAAO,EAAE,KAAK,SAAS,GAAG;IAC5B,SAAS,KAAK;KACZ,OAAO,cAAc,GAAG,GAAG;IAC7B;GACF;EACF,CAAC;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-worker.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/github/event-worker.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAG1D,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,+CAA+C,CAAC;AAE9F,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,kCAAkC,CAAC;AACxF,OAAO,KAAK,EAAE,2BAA2B,EAAuB,MAAM,uBAAuB,CAAC;AAE9F,OAAO,EAAE,qBAAqB,EAA6C,MAAM,yBAAyB,CAAC;AAC3G,OAAO,KAAK,EACV,gCAAgC,EAEhC,mBAAmB,EACpB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAmC1D,KAAK,WAAW,GAAG;IAAE,YAAY,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,cAAc,EAAE,MAAM,CAAA;CAAE,CAAC;AACzE,KAAK,iCAAiC,GAAG;IACvC,OAAO,EAAE,CAAC,CAAC;IACX,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;CAC3C,CAAC;AAEF,MAAM,MAAM,0BAA0B,GAAG,wBAAwB,CAC/D,MAAM,CAAC,MAAM,E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;OAMG;IACH,aAAa,EAAE,+BAA+B,CAAC;IAC/C,kBAAkB,CAAC,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACtE,qBAAqB,CAAC,EAAE,2BAA2B,CAAC;IACpD,2BAA2B,CAAC,EAAE,qBAAqB,CAAC;IACpD,6FAA6F;IAC7F,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,4CAA4C;IAC5C,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,8BAA8B,CAAC,EAAE,MAAM,CAAC;IACxC,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,OAAO,qBAAqB,CAAC;CACzC;AAED,qBAAa,yBAA0B,SAAQ,YAAY;;IACzD,QAAQ,CAAC,IAAI,4BAA4B;gBA+B7B,MAAM,EAAE,+BAA+B;IAgC7C,IAAI,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAKrC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IActB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAa3B,IAAI,SAAS,IAAI,OAAO,CAEvB;CAwWF"}
|
|
@@ -250,6 +250,7 @@ var PlatformGithubEventWorker = class extends MastraWorker {
|
|
|
250
250
|
...context,
|
|
251
251
|
errors
|
|
252
252
|
});
|
|
253
|
+
else if (counts.created > 0) this.deps?.logger.info("Platform GitHub issue reconcile replayed missed opens", context);
|
|
253
254
|
else if (counts.closed > 0) this.deps?.logger.info("Platform GitHub issue reconcile replayed closed work items", context);
|
|
254
255
|
else if (counts.updated > 0) this.deps?.logger.info("Platform GitHub issue reconcile patched stale metadata", context);
|
|
255
256
|
else this.deps?.logger.debug("Platform GitHub issue reconcile sweep completed", context);
|
|
@@ -320,6 +321,12 @@ var PlatformGithubEventWorker = class extends MastraWorker {
|
|
|
320
321
|
continue;
|
|
321
322
|
}
|
|
322
323
|
if (isFactoryIngestedEvent(parsed)) await this.#ingestFactoryEvent?.(parsed);
|
|
324
|
+
else this.deps?.logger.debug("Platform GitHub event not forwarded to Factory ingress", {
|
|
325
|
+
repositoryId,
|
|
326
|
+
deliveryId: parsed.deliveryId,
|
|
327
|
+
event: parsed.event,
|
|
328
|
+
action: parsed.payload.action
|
|
329
|
+
});
|
|
323
330
|
const result = await this.#dispatch(parsed, {
|
|
324
331
|
controller: this.#controller,
|
|
325
332
|
listSubscriptions: (target, options) => listPullRequestSubscriptionsForWebhook(target, options, this.#github.integrationStorage),
|
|
@@ -406,12 +413,20 @@ function normalizeSettings(value) {
|
|
|
406
413
|
repositories: { ...value.repositories }
|
|
407
414
|
};
|
|
408
415
|
}
|
|
416
|
+
const ISSUE_INGESTED_ACTIONS = /* @__PURE__ */ new Set([
|
|
417
|
+
"opened",
|
|
418
|
+
"reopened",
|
|
419
|
+
"edited",
|
|
420
|
+
"labeled",
|
|
421
|
+
"unlabeled"
|
|
422
|
+
]);
|
|
409
423
|
function isFactoryIngestedEvent(event) {
|
|
410
424
|
if ((event.event === "issues" || event.event === "pull_request") && event.payload.action === "closed") return true;
|
|
411
425
|
if (event.event === "pull_request") {
|
|
412
426
|
const action = event.payload.action;
|
|
413
427
|
if (action === "opened" || action === "synchronize" || action === "review_requested") return true;
|
|
414
428
|
}
|
|
429
|
+
if (event.event === "issues" && ISSUE_INGESTED_ACTIONS.has(String(event.payload.action))) return true;
|
|
415
430
|
if (event.event === "pull_request_review" && event.payload.action === "submitted") return true;
|
|
416
431
|
if (event.event === "issue_comment" && event.payload.action === "created") return true;
|
|
417
432
|
if (event.event === "push") return true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-worker.js","names":["#client","#controller","#github","#storage","#ingestFactoryEvent","#reconcileFactoryState","#reconcileIssuesFactoryState","#pollEventsEnabled","#pullRequestReconcileIntervalMs","#issueReconcileIntervalMs","#intervalMs","#now","#dispatch","#sourceControl","#leaseOwner","#leaseTtlMs","#leaseProvider","#running","#startedAt","#settings","#schedule","#timer","#stopLeaseRenewal","#inFlight","#hasLease","#leaseKey","#tick","#ensureLease","#poll","#startLeaseRenewal","#leaseRenewalTimer","#discoverRepositories","#reconcileCadence","#pollRepository","#maybeReconcile","#lastPullRequestReconcileAt","#lastIssueReconcileAt","#saveSettings","#isAuthorizedSender"],"sources":["../../../../src/integrations/platform/github/event-worker.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { MountedMastraCode } from '@mastra/code-sdk';\nimport { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { GithubRepositoryPermission } from '../../github/integration.js';\nimport type { GithubIssueReconciler } from '../../github/issue-reconciler.js';\nimport type { GithubReconcileRepositorySource } from '../../github/reconcile-worker.js';\nimport type { GithubPullRequestReconciler, ReconcileRepository } from '../../github/rules.js';\nimport { listPullRequestSubscriptionsForWebhook, retirePullRequestSubscription } from '../../github/subscriptions.js';\nimport { dispatchGithubWebhook, isFactoryAppSender, resolveAuthorizedBots } from '../../github/webhook.js';\nimport type {\n GithubWebhookDispatchIntegration,\n GithubWebhookNotification,\n ParsedGithubWebhook,\n} from '../../github/webhook.js';\nimport type { PlatformApiClient } from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\n\nconst API_PREFIX = '/v1/server/github-app';\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\n// Event polling is the primary sync; the sweeps only catch drift (missed\n// events, cards ingested before polling was linked), so they run hourly.\nconst DEFAULT_RECONCILE_INTERVAL_MS = 60 * 60_000;\nconst EVENT_PAGE_SIZE = 500;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_github_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst SUPPORTED_EVENTS = new Set([\n 'issues',\n 'issue_comment',\n 'pull_request',\n 'pull_request_review',\n 'pull_request_review_comment',\n // Pushes never reach the subscription dispatcher; they feed the factory\n // ingest path so base checkpoints rebuild on default-branch updates.\n 'push',\n]);\n// Kinds emitted by `classifyGithubWebhook` that carry untrusted sender-authored\n// content and must pass the sender authorization gate below.\nconst AUTHOR_GATED_KINDS = new Set([\n 'issue-comment-created',\n 'review-comment-created',\n 'review-approved',\n 'review-changes-requested',\n 'review-submitted',\n 'review-dismissed',\n]);\nconst AUTHORIZED_PERMISSIONS = new Set<GithubRepositoryPermission>(['admin', 'maintain', 'write']);\nconst PERMISSION_CHECK_TIMEOUT_MS = 5_000;\n\ntype EventCursor = { afterEventId: string } | { afterTimestamp: number };\ntype PlatformGithubEventWorkerSettings = {\n version: 1;\n repositories: Record<string, EventCursor>;\n};\n\nexport type PlatformGithubEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformGithubEventWorkerSettings,\n Record<string, unknown>\n>;\n\ntype EventLogEntry = {\n id: string;\n deliveryId: string;\n event: string;\n payload: unknown;\n};\n\ntype Repository = { id: number; fullName?: string; installationId: number };\n\nexport type PlatformGithubEventDispatchIntegration = GithubWebhookDispatchIntegration;\n\nexport interface PlatformGithubEventWorkerConfig {\n client: PlatformApiClient;\n controller: MountedMastraCode['controller'];\n github: PlatformGithubEventDispatchIntegration;\n storage: PlatformGithubEventStorage;\n /**\n * Source-control storage used to resolve the set of repositories the worker\n * should poll. The worker restricts itself to `(installation, repository)`\n * pairs linked to a factory project — the same set the reconciler uses —\n * so polling scales with Factory usage, not with the size of the underlying\n * GitHub org.\n */\n sourceControl: GithubReconcileRepositorySource;\n ingestFactoryEvent?: (event: ParsedGithubWebhook) => Promise<unknown>;\n reconcileFactoryState?: GithubPullRequestReconciler;\n reconcileIssuesFactoryState?: GithubIssueReconciler;\n /** When false the worker skips event tailing and only runs enabled reconciliation sweeps. */\n pollEventsEnabled?: boolean;\n intervalMs?: number;\n /** Legacy shared reconciliation cadence. */\n reconcileIntervalMs?: number;\n pullRequestReconcileIntervalMs?: number;\n issueReconcileIntervalMs?: number;\n now?: () => number;\n dispatch?: typeof dispatchGithubWebhook;\n}\n\nexport class PlatformGithubEventWorker extends MastraWorker {\n readonly name = 'platform-github-events';\n\n readonly #client: PlatformApiClient;\n readonly #controller: MountedMastraCode['controller'];\n readonly #github: PlatformGithubEventDispatchIntegration;\n readonly #storage: PlatformGithubEventStorage;\n readonly #ingestFactoryEvent: ((event: ParsedGithubWebhook) => Promise<unknown>) | undefined;\n readonly #reconcileFactoryState: GithubPullRequestReconciler | undefined;\n readonly #reconcileIssuesFactoryState: GithubIssueReconciler | undefined;\n readonly #pollEventsEnabled: boolean;\n readonly #pullRequestReconcileIntervalMs: number;\n readonly #issueReconcileIntervalMs: number;\n readonly #intervalMs: number;\n readonly #now: () => number;\n readonly #dispatch: typeof dispatchGithubWebhook;\n readonly #sourceControl: GithubReconcileRepositorySource;\n readonly #leaseOwner = randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n // Negative infinity so the first tick always sweeps, whatever the clock reads.\n #lastPullRequestReconcileAt = Number.NEGATIVE_INFINITY;\n #lastIssueReconcileAt = Number.NEGATIVE_INFINITY;\n #settings: PlatformGithubEventWorkerSettings = { version: 1, repositories: {} };\n\n constructor(config: PlatformGithubEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#controller = config.controller;\n this.#github = config.github;\n this.#storage = config.storage;\n this.#ingestFactoryEvent = config.ingestFactoryEvent;\n this.#reconcileFactoryState = config.reconcileFactoryState;\n this.#reconcileIssuesFactoryState = config.reconcileIssuesFactoryState;\n this.#pollEventsEnabled = config.pollEventsEnabled ?? true;\n const legacyReconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;\n this.#pullRequestReconcileIntervalMs = config.pullRequestReconcileIntervalMs ?? legacyReconcileIntervalMs;\n this.#issueReconcileIntervalMs = config.issueReconcileIntervalMs ?? legacyReconcileIntervalMs;\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform GitHub event polling interval must be a positive number.');\n }\n if (!Number.isFinite(this.#pullRequestReconcileIntervalMs) || this.#pullRequestReconcileIntervalMs <= 0) {\n throw new Error('Platform GitHub pull request reconcile interval must be a positive number.');\n }\n if (!Number.isFinite(this.#issueReconcileIntervalMs) || this.#issueReconcileIntervalMs <= 0) {\n throw new Error('Platform GitHub issue reconcile interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(\n MIN_LEASE_TTL_MS,\n Math.min(this.#intervalMs, this.#pullRequestReconcileIntervalMs, this.#issueReconcileIntervalMs) * 3,\n );\n this.#now = config.now ?? Date.now;\n this.#dispatch = config.dispatch ?? dispatchGithubWebhook;\n this.#sourceControl = config.sourceControl;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformGithubEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#running = true;\n this.deps.logger.info('Platform GitHub event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform GitHub event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform GitHub event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n const repositories = await this.#discoverRepositories();\n let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileCadence();\n\n if (this.#pollEventsEnabled) {\n for (const repository of repositories) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollRepository(repository.id);\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform GitHub repository event polling failed', {\n repositoryId: repository.id,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n }\n\n await this.#maybeReconcile(repositories);\n return retryInMs;\n }\n\n #reconcileCadence(): number {\n const cadences = [\n this.#reconcileFactoryState ? this.#pullRequestReconcileIntervalMs : undefined,\n this.#reconcileIssuesFactoryState ? this.#issueReconcileIntervalMs : undefined,\n ].filter((interval): interval is number => interval !== undefined);\n return cadences.length > 0 ? Math.min(...cadences) : this.#intervalMs;\n }\n\n async #maybeReconcile(repositories: Repository[]): Promise<void> {\n if (!this.#running || !this.#hasLease) return;\n const now = this.#now();\n const reconcilePullRequests = Boolean(\n this.#reconcileFactoryState && now - this.#lastPullRequestReconcileAt >= this.#pullRequestReconcileIntervalMs,\n );\n const reconcileIssues = Boolean(\n this.#reconcileIssuesFactoryState && now - this.#lastIssueReconcileAt >= this.#issueReconcileIntervalMs,\n );\n if (!reconcilePullRequests && !reconcileIssues) return;\n if (reconcilePullRequests) this.#lastPullRequestReconcileAt = now;\n if (reconcileIssues) this.#lastIssueReconcileAt = now;\n\n const targets: ReconcileRepository[] = repositories.flatMap(repository =>\n repository.fullName\n ? [{ id: repository.id, fullName: repository.fullName, installationId: repository.installationId }]\n : [],\n );\n if (targets.length === 0) {\n this.deps?.logger.debug('Platform GitHub reconciliation skipped: no named repositories');\n return;\n }\n\n if (reconcilePullRequests && this.#reconcileFactoryState) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileFactoryState(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub pull request reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.merged > 0 || counts.closed > 0) {\n this.deps?.logger.info('Platform GitHub pull request reconcile replayed missed merges/closes', context);\n } else {\n this.deps?.logger.info('Platform GitHub pull request reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub pull request reconcile failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (reconcileIssues && this.#reconcileIssuesFactoryState && this.#hasLease) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileIssuesFactoryState(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub issue reconcile sweep completed with failures', { ...context, errors });\n } else if (counts.closed > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile replayed closed work items', context);\n } else if (counts.updated > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile patched stale metadata', context);\n } else {\n this.deps?.logger.debug('Platform GitHub issue reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub issue reconcile failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n }\n\n /**\n * Configured `(installation, repository)` pairs — the same set the\n * reconciler sweeps — resolved to the numeric ids and slug the poll\n * addresses GitHub with. Repositories not linked to any factory project\n * cannot produce work for Factory, so polling and reconciling them is\n * wasted `/events` bandwidth and platform load.\n */\n async #discoverRepositories(): Promise<Repository[]> {\n const keys = await this.#sourceControl.projectRepositories.listConfiguredExternalKeys();\n const repositories = new Map<number, Repository>();\n for (const key of keys) {\n const installationId = Number(key.installationExternalId);\n const repositoryId = Number(key.repositoryExternalId);\n if (\n !Number.isSafeInteger(installationId) ||\n installationId <= 0 ||\n !Number.isSafeInteger(repositoryId) ||\n repositoryId <= 0\n ) {\n continue;\n }\n if (repositories.has(repositoryId)) continue;\n // A configured key exists per project link, so `listByExternalRepository`\n // always yields at least one row; the first row's orgId is enough to\n // look up the repository row for its slug.\n const projects = await this.#sourceControl.projectRepositories.listByExternalRepository(key);\n const orgId = projects[0]?.orgId;\n const repository = orgId\n ? await this.#sourceControl.repositories.findByExternalId({ orgId, externalId: key.repositoryExternalId })\n : null;\n repositories.set(repositoryId, {\n id: repositoryId,\n installationId,\n fullName: repository?.slug,\n });\n }\n return [...repositories.values()];\n }\n\n async #pollRepository(repositoryId: number): Promise<void> {\n const key = String(repositoryId);\n if (!this.#settings.repositories[key]) {\n this.#settings.repositories[key] = { afterTimestamp: this.#startedAt };\n await this.#saveSettings();\n }\n\n while (this.#running && this.#hasLease) {\n const cursor: EventCursor = this.#settings.repositories[key]!;\n const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE) });\n if ('afterEventId' in cursor) query.set('afterEventId', cursor.afterEventId);\n else query.set('afterTimestamp', String(cursor.afterTimestamp));\n\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: EventLogEntry[]; nextCursor: string | null }>(\n 'GET',\n `${API_PREFIX}/repositories/${repositoryId}/events?${query}`,\n );\n this.deps?.logger.debug('Platform GitHub repository event poll completed', {\n repositoryId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0 || !page.nextCursor) return;\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n const parsed = parseEvent(event);\n if (!parsed) {\n this.deps?.logger.warn('Platform GitHub event log returned a malformed event', {\n repositoryId,\n eventId: event.id,\n });\n continue;\n }\n if (isFactoryIngestedEvent(parsed)) {\n await this.#ingestFactoryEvent?.(parsed);\n }\n const result = await this.#dispatch(parsed, {\n controller: this.#controller,\n listSubscriptions: (target, options) =>\n listPullRequestSubscriptionsForWebhook(target, options, this.#github.integrationStorage),\n retireSubscription: (id, status) =>\n retirePullRequestSubscription(id, status, this.#github.integrationStorage),\n github: this.#github,\n isAuthorizedSender: notification => this.#isAuthorizedSender(notification),\n onTargetSkipped: subscription => {\n // Routine when a subscription's thread belongs to another\n // deployment, so this stays at debug rather than warning on a loop.\n this.deps?.logger.debug('Platform GitHub event skipped: thread is not held here', {\n deliveryId: event.deliveryId,\n subscriptionId: subscription.id,\n threadId: subscription.threadId,\n });\n },\n onSenderRejected: notification => {\n this.deps?.logger.debug('Platform GitHub event dropped: sender not authorized', {\n deliveryId: event.deliveryId,\n repository: notification.metadata.repository,\n sender: notification.metadata.sender,\n kind: notification.kind,\n });\n },\n onTargetError: (subscription, error) => {\n this.deps?.logger.error('Platform GitHub event delivery failed for a subscription', {\n deliveryId: event.deliveryId,\n subscriptionId: subscription.id,\n resourceId: subscription.resourceId,\n threadId: subscription.threadId,\n error: error instanceof Error ? error.message : String(error),\n });\n },\n });\n if (result.failed > 0) {\n this.deps?.logger.warn('Platform GitHub event completed with failed subscription deliveries', {\n repositoryId,\n deliveryId: event.deliveryId,\n delivered: result.delivered,\n failed: result.failed,\n });\n }\n }\n\n if (page.nextCursor === ('afterEventId' in cursor ? cursor.afterEventId : undefined)) return;\n this.#settings.repositories[key] = { afterEventId: page.nextCursor };\n await this.#saveSettings();\n }\n }\n\n async #isAuthorizedSender(notification: GithubWebhookNotification): Promise<boolean> {\n if (!AUTHOR_GATED_KINDS.has(notification.kind)) return true;\n const sender = notification.metadata.sender;\n const repository = notification.metadata.repository;\n if (!sender || !repository) return false;\n // Factory's own app has to clear the gate before the bot rules below, which\n // fail closed for every bot that is not explicitly allowlisted. GitHub\n // forbids an app from reviewing its own pull request, so `factory-review`\n // posts its verdict as a comment under this login and that comment is the\n // handoff the authoring agent wakes on.\n if (this.#github.identity?.matches(sender)) return true;\n if (isFactoryAppSender(sender, this.#github.slug)) return true;\n const normalizedSender = sender.toLowerCase();\n const authorizedBots = resolveAuthorizedBots(this.#github.authorizedBots);\n if (authorizedBots.has(normalizedSender)) return true;\n // Any other bot is gated purely by the allowlist: a GitHub App never holds a\n // collaborator permission under its sender login, so falling through to the\n // permission lookup would only fail closed after a wasted API call.\n if (notification.metadata.senderType?.toLowerCase() === 'bot' || normalizedSender.endsWith('[bot]')) {\n return false;\n }\n\n const abortController = new AbortController();\n const timeout = setTimeout(() => abortController.abort(), PERMISSION_CHECK_TIMEOUT_MS);\n try {\n const permission = await this.#github.getRepositoryCollaboratorPermission(\n notification.metadata.installationId,\n repository,\n sender,\n abortController.signal,\n );\n return permission !== undefined && AUTHORIZED_PERMISSIONS.has(permission);\n } catch {\n return false;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\n }\n\n #leaseKey(): string {\n return `${this.name}:${this.#storage.integrationId}`;\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformGithubEventWorkerSettings | null): PlatformGithubEventWorkerSettings {\n if (!value || value.version !== 1 || !value.repositories || typeof value.repositories !== 'object') {\n return { version: 1, repositories: {} };\n }\n return { version: 1, repositories: { ...value.repositories } };\n}\n\n// Events the polling worker forwards to the factory rules engine. Closures\n// let the reconciler finalize cards; `synchronize` and `review_requested` on a\n// pull request are the triggers the review board's re-review path listens for;\n// submitted reviews and pull request comments are how review feedback reaches\n// the agent that authored the branch. Direct-webhook consumers ingest every\n// parsed event; the platform path gates because the remaining events (issue\n// edits, comment edits and deletions) only interest the subscription\n// dispatcher, not the factory rules.\nfunction isFactoryIngestedEvent(event: ParsedGithubWebhook): boolean {\n if ((event.event === 'issues' || event.event === 'pull_request') && event.payload.action === 'closed') {\n return true;\n }\n if (event.event === 'pull_request') {\n const action = event.payload.action;\n // `opened` is what mints the Review card for a pull request. Without it a\n // factory-authored PR never gets reviewed on the polling path, which is the\n // only path a local deployment has.\n if (action === 'opened' || action === 'synchronize' || action === 'review_requested') return true;\n }\n if (event.event === 'pull_request_review' && event.payload.action === 'submitted') return true;\n if (event.event === 'issue_comment' && event.payload.action === 'created') return true;\n // Default-branch pushes drive base-checkpoint rebuilds\n // (`withBaseCheckpointWebhookTrigger` wraps the ingest callback).\n if (event.event === 'push') return true;\n return false;\n}\n\nfunction parseEvent(event: EventLogEntry): ParsedGithubWebhook | null {\n if (\n !event.id ||\n !event.deliveryId ||\n !SUPPORTED_EVENTS.has(event.event) ||\n !event.payload ||\n typeof event.payload !== 'object' ||\n Array.isArray(event.payload)\n ) {\n return null;\n }\n return {\n event: event.event,\n deliveryId: event.deliveryId,\n payload: event.payload as Record<string, unknown>,\n };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\n}\n"],"mappings":";;;;;;;AAuBA,MAAM,aAAa;AACnB,MAAM,2BAA2B;AAGjC,MAAM,gCAAgC,KAAK;AAC3C,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,mCAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;CACA;CAGA;AACF,CAAC;AAGD,MAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,yCAAyB,IAAI,IAAgC;CAAC;CAAS;CAAY;AAAO,CAAC;AACjG,MAAM,8BAA8B;AAoDpC,IAAa,4BAAb,cAA+C,aAAa;CAC1D,OAAgB;CAEhB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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EACb,YAAY,MAAM;EAClB,SAAS,MAAM;CACjB;AACF;AAEA,SAAS,WAAW,OAAgB,YAA4B;CAC9D,IAAI,iBAAiB,oBAAoB,MAAM,WAAW,OAAO,MAAM,sBAAsB,MAC3F,OAAO,KAAK,IAAI,YAAY,MAAM,oBAAoB,GAAK;CAE7D,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"event-worker.js","names":["#client","#controller","#github","#storage","#ingestFactoryEvent","#reconcileFactoryState","#reconcileIssuesFactoryState","#pollEventsEnabled","#pullRequestReconcileIntervalMs","#issueReconcileIntervalMs","#intervalMs","#now","#dispatch","#sourceControl","#leaseOwner","#leaseTtlMs","#leaseProvider","#running","#startedAt","#settings","#schedule","#timer","#stopLeaseRenewal","#inFlight","#hasLease","#leaseKey","#tick","#ensureLease","#poll","#startLeaseRenewal","#leaseRenewalTimer","#discoverRepositories","#reconcileCadence","#pollRepository","#maybeReconcile","#lastPullRequestReconcileAt","#lastIssueReconcileAt","#saveSettings","#isAuthorizedSender"],"sources":["../../../../src/integrations/platform/github/event-worker.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { MountedMastraCode } from '@mastra/code-sdk';\nimport { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { GithubRepositoryPermission } from '../../github/integration.js';\nimport type { GithubIssueReconciler } from '../../github/issue-reconciler.js';\nimport type { GithubReconcileRepositorySource } from '../../github/reconcile-worker.js';\nimport type { GithubPullRequestReconciler, ReconcileRepository } from '../../github/rules.js';\nimport { listPullRequestSubscriptionsForWebhook, retirePullRequestSubscription } from '../../github/subscriptions.js';\nimport { dispatchGithubWebhook, isFactoryAppSender, resolveAuthorizedBots } from '../../github/webhook.js';\nimport type {\n GithubWebhookDispatchIntegration,\n GithubWebhookNotification,\n ParsedGithubWebhook,\n} from '../../github/webhook.js';\nimport type { PlatformApiClient } from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\n\nconst API_PREFIX = '/v1/server/github-app';\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\n// Event polling is the primary sync; the sweeps only catch drift (missed\n// events, cards ingested before polling was linked), so they run hourly.\nconst DEFAULT_RECONCILE_INTERVAL_MS = 60 * 60_000;\nconst EVENT_PAGE_SIZE = 500;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_github_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst SUPPORTED_EVENTS = new Set([\n 'issues',\n 'issue_comment',\n 'pull_request',\n 'pull_request_review',\n 'pull_request_review_comment',\n // Pushes never reach the subscription dispatcher; they feed the factory\n // ingest path so base checkpoints rebuild on default-branch updates.\n 'push',\n]);\n// Kinds emitted by `classifyGithubWebhook` that carry untrusted sender-authored\n// content and must pass the sender authorization gate below.\nconst AUTHOR_GATED_KINDS = new Set([\n 'issue-comment-created',\n 'review-comment-created',\n 'review-approved',\n 'review-changes-requested',\n 'review-submitted',\n 'review-dismissed',\n]);\nconst AUTHORIZED_PERMISSIONS = new Set<GithubRepositoryPermission>(['admin', 'maintain', 'write']);\nconst PERMISSION_CHECK_TIMEOUT_MS = 5_000;\n\ntype EventCursor = { afterEventId: string } | { afterTimestamp: number };\ntype PlatformGithubEventWorkerSettings = {\n version: 1;\n repositories: Record<string, EventCursor>;\n};\n\nexport type PlatformGithubEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformGithubEventWorkerSettings,\n Record<string, unknown>\n>;\n\ntype EventLogEntry = {\n id: string;\n deliveryId: string;\n event: string;\n payload: unknown;\n};\n\ntype Repository = { id: number; fullName?: string; installationId: number };\n\nexport type PlatformGithubEventDispatchIntegration = GithubWebhookDispatchIntegration;\n\nexport interface PlatformGithubEventWorkerConfig {\n client: PlatformApiClient;\n controller: MountedMastraCode['controller'];\n github: PlatformGithubEventDispatchIntegration;\n storage: PlatformGithubEventStorage;\n /**\n * Source-control storage used to resolve the set of repositories the worker\n * should poll. The worker restricts itself to `(installation, repository)`\n * pairs linked to a factory project — the same set the reconciler uses —\n * so polling scales with Factory usage, not with the size of the underlying\n * GitHub org.\n */\n sourceControl: GithubReconcileRepositorySource;\n ingestFactoryEvent?: (event: ParsedGithubWebhook) => Promise<unknown>;\n reconcileFactoryState?: GithubPullRequestReconciler;\n reconcileIssuesFactoryState?: GithubIssueReconciler;\n /** When false the worker skips event tailing and only runs enabled reconciliation sweeps. */\n pollEventsEnabled?: boolean;\n intervalMs?: number;\n /** Legacy shared reconciliation cadence. */\n reconcileIntervalMs?: number;\n pullRequestReconcileIntervalMs?: number;\n issueReconcileIntervalMs?: number;\n now?: () => number;\n dispatch?: typeof dispatchGithubWebhook;\n}\n\nexport class PlatformGithubEventWorker extends MastraWorker {\n readonly name = 'platform-github-events';\n\n readonly #client: PlatformApiClient;\n readonly #controller: MountedMastraCode['controller'];\n readonly #github: PlatformGithubEventDispatchIntegration;\n readonly #storage: PlatformGithubEventStorage;\n readonly #ingestFactoryEvent: ((event: ParsedGithubWebhook) => Promise<unknown>) | undefined;\n readonly #reconcileFactoryState: GithubPullRequestReconciler | undefined;\n readonly #reconcileIssuesFactoryState: GithubIssueReconciler | undefined;\n readonly #pollEventsEnabled: boolean;\n readonly #pullRequestReconcileIntervalMs: number;\n readonly #issueReconcileIntervalMs: number;\n readonly #intervalMs: number;\n readonly #now: () => number;\n readonly #dispatch: typeof dispatchGithubWebhook;\n readonly #sourceControl: GithubReconcileRepositorySource;\n readonly #leaseOwner = randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n // Negative infinity so the first tick always sweeps, whatever the clock reads.\n #lastPullRequestReconcileAt = Number.NEGATIVE_INFINITY;\n #lastIssueReconcileAt = Number.NEGATIVE_INFINITY;\n #settings: PlatformGithubEventWorkerSettings = { version: 1, repositories: {} };\n\n constructor(config: PlatformGithubEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#controller = config.controller;\n this.#github = config.github;\n this.#storage = config.storage;\n this.#ingestFactoryEvent = config.ingestFactoryEvent;\n this.#reconcileFactoryState = config.reconcileFactoryState;\n this.#reconcileIssuesFactoryState = config.reconcileIssuesFactoryState;\n this.#pollEventsEnabled = config.pollEventsEnabled ?? true;\n const legacyReconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;\n this.#pullRequestReconcileIntervalMs = config.pullRequestReconcileIntervalMs ?? legacyReconcileIntervalMs;\n this.#issueReconcileIntervalMs = config.issueReconcileIntervalMs ?? legacyReconcileIntervalMs;\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform GitHub event polling interval must be a positive number.');\n }\n if (!Number.isFinite(this.#pullRequestReconcileIntervalMs) || this.#pullRequestReconcileIntervalMs <= 0) {\n throw new Error('Platform GitHub pull request reconcile interval must be a positive number.');\n }\n if (!Number.isFinite(this.#issueReconcileIntervalMs) || this.#issueReconcileIntervalMs <= 0) {\n throw new Error('Platform GitHub issue reconcile interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(\n MIN_LEASE_TTL_MS,\n Math.min(this.#intervalMs, this.#pullRequestReconcileIntervalMs, this.#issueReconcileIntervalMs) * 3,\n );\n this.#now = config.now ?? Date.now;\n this.#dispatch = config.dispatch ?? dispatchGithubWebhook;\n this.#sourceControl = config.sourceControl;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformGithubEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#running = true;\n this.deps.logger.info('Platform GitHub event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform GitHub event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform GitHub event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n const repositories = await this.#discoverRepositories();\n let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileCadence();\n\n if (this.#pollEventsEnabled) {\n for (const repository of repositories) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollRepository(repository.id);\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform GitHub repository event polling failed', {\n repositoryId: repository.id,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n }\n\n await this.#maybeReconcile(repositories);\n return retryInMs;\n }\n\n #reconcileCadence(): number {\n const cadences = [\n this.#reconcileFactoryState ? this.#pullRequestReconcileIntervalMs : undefined,\n this.#reconcileIssuesFactoryState ? this.#issueReconcileIntervalMs : undefined,\n ].filter((interval): interval is number => interval !== undefined);\n return cadences.length > 0 ? Math.min(...cadences) : this.#intervalMs;\n }\n\n async #maybeReconcile(repositories: Repository[]): Promise<void> {\n if (!this.#running || !this.#hasLease) return;\n const now = this.#now();\n const reconcilePullRequests = Boolean(\n this.#reconcileFactoryState && now - this.#lastPullRequestReconcileAt >= this.#pullRequestReconcileIntervalMs,\n );\n const reconcileIssues = Boolean(\n this.#reconcileIssuesFactoryState && now - this.#lastIssueReconcileAt >= this.#issueReconcileIntervalMs,\n );\n if (!reconcilePullRequests && !reconcileIssues) return;\n if (reconcilePullRequests) this.#lastPullRequestReconcileAt = now;\n if (reconcileIssues) this.#lastIssueReconcileAt = now;\n\n const targets: ReconcileRepository[] = repositories.flatMap(repository =>\n repository.fullName\n ? [{ id: repository.id, fullName: repository.fullName, installationId: repository.installationId }]\n : [],\n );\n if (targets.length === 0) {\n this.deps?.logger.debug('Platform GitHub reconciliation skipped: no named repositories');\n return;\n }\n\n if (reconcilePullRequests && this.#reconcileFactoryState) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileFactoryState(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub pull request reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.merged > 0 || counts.closed > 0) {\n this.deps?.logger.info('Platform GitHub pull request reconcile replayed missed merges/closes', context);\n } else {\n this.deps?.logger.info('Platform GitHub pull request reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub pull request reconcile failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (reconcileIssues && this.#reconcileIssuesFactoryState && this.#hasLease) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileIssuesFactoryState(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub issue reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.created > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile replayed missed opens', context);\n } else if (counts.closed > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile replayed closed work items', context);\n } else if (counts.updated > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile patched stale metadata', context);\n } else {\n this.deps?.logger.debug('Platform GitHub issue reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub issue reconcile failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n /**\n * Configured `(installation, repository)` pairs — the same set the\n * reconciler sweeps — resolved to the numeric ids and slug the poll\n * addresses GitHub with. Repositories not linked to any factory project\n * cannot produce work for Factory, so polling and reconciling them is\n * wasted `/events` bandwidth and platform load.\n */\n async #discoverRepositories(): Promise<Repository[]> {\n const keys = await this.#sourceControl.projectRepositories.listConfiguredExternalKeys();\n const repositories = new Map<number, Repository>();\n for (const key of keys) {\n const installationId = Number(key.installationExternalId);\n const repositoryId = Number(key.repositoryExternalId);\n if (\n !Number.isSafeInteger(installationId) ||\n installationId <= 0 ||\n !Number.isSafeInteger(repositoryId) ||\n repositoryId <= 0\n ) {\n continue;\n }\n if (repositories.has(repositoryId)) continue;\n // A configured key exists per project link, so `listByExternalRepository`\n // always yields at least one row; the first row's orgId is enough to\n // look up the repository row for its slug.\n const projects = await this.#sourceControl.projectRepositories.listByExternalRepository(key);\n const orgId = projects[0]?.orgId;\n const repository = orgId\n ? await this.#sourceControl.repositories.findByExternalId({ orgId, externalId: key.repositoryExternalId })\n : null;\n repositories.set(repositoryId, {\n id: repositoryId,\n installationId,\n fullName: repository?.slug,\n });\n }\n return [...repositories.values()];\n }\n\n async #pollRepository(repositoryId: number): Promise<void> {\n const key = String(repositoryId);\n if (!this.#settings.repositories[key]) {\n this.#settings.repositories[key] = { afterTimestamp: this.#startedAt };\n await this.#saveSettings();\n }\n\n while (this.#running && this.#hasLease) {\n const cursor: EventCursor = this.#settings.repositories[key]!;\n const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE) });\n if ('afterEventId' in cursor) query.set('afterEventId', cursor.afterEventId);\n else query.set('afterTimestamp', String(cursor.afterTimestamp));\n\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: EventLogEntry[]; nextCursor: string | null }>(\n 'GET',\n `${API_PREFIX}/repositories/${repositoryId}/events?${query}`,\n );\n this.deps?.logger.debug('Platform GitHub repository event poll completed', {\n repositoryId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0 || !page.nextCursor) return;\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n const parsed = parseEvent(event);\n if (!parsed) {\n this.deps?.logger.warn('Platform GitHub event log returned a malformed event', {\n repositoryId,\n eventId: event.id,\n });\n continue;\n }\n if (isFactoryIngestedEvent(parsed)) {\n await this.#ingestFactoryEvent?.(parsed);\n } else {\n this.deps?.logger.debug('Platform GitHub event not forwarded to Factory ingress', {\n repositoryId,\n deliveryId: parsed.deliveryId,\n event: parsed.event,\n action: parsed.payload.action,\n });\n }\n const result = await this.#dispatch(parsed, {\n controller: this.#controller,\n listSubscriptions: (target, options) =>\n listPullRequestSubscriptionsForWebhook(target, options, this.#github.integrationStorage),\n retireSubscription: (id, status) =>\n retirePullRequestSubscription(id, status, this.#github.integrationStorage),\n github: this.#github,\n isAuthorizedSender: notification => this.#isAuthorizedSender(notification),\n onTargetSkipped: subscription => {\n // Routine when a subscription's thread belongs to another\n // deployment, so this stays at debug rather than warning on a loop.\n this.deps?.logger.debug('Platform GitHub event skipped: thread is not held here', {\n deliveryId: event.deliveryId,\n subscriptionId: subscription.id,\n threadId: subscription.threadId,\n });\n },\n onSenderRejected: notification => {\n this.deps?.logger.debug('Platform GitHub event dropped: sender not authorized', {\n deliveryId: event.deliveryId,\n repository: notification.metadata.repository,\n sender: notification.metadata.sender,\n kind: notification.kind,\n });\n },\n onTargetError: (subscription, error) => {\n this.deps?.logger.error('Platform GitHub event delivery failed for a subscription', {\n deliveryId: event.deliveryId,\n subscriptionId: subscription.id,\n resourceId: subscription.resourceId,\n threadId: subscription.threadId,\n error: error instanceof Error ? error.message : String(error),\n });\n },\n });\n if (result.failed > 0) {\n this.deps?.logger.warn('Platform GitHub event completed with failed subscription deliveries', {\n repositoryId,\n deliveryId: event.deliveryId,\n delivered: result.delivered,\n failed: result.failed,\n });\n }\n }\n\n if (page.nextCursor === ('afterEventId' in cursor ? cursor.afterEventId : undefined)) return;\n this.#settings.repositories[key] = { afterEventId: page.nextCursor };\n await this.#saveSettings();\n }\n }\n\n async #isAuthorizedSender(notification: GithubWebhookNotification): Promise<boolean> {\n if (!AUTHOR_GATED_KINDS.has(notification.kind)) return true;\n const sender = notification.metadata.sender;\n const repository = notification.metadata.repository;\n if (!sender || !repository) return false;\n // Factory's own app has to clear the gate before the bot rules below, which\n // fail closed for every bot that is not explicitly allowlisted. GitHub\n // forbids an app from reviewing its own pull request, so `factory-review`\n // posts its verdict as a comment under this login and that comment is the\n // handoff the authoring agent wakes on.\n if (this.#github.identity?.matches(sender)) return true;\n if (isFactoryAppSender(sender, this.#github.slug)) return true;\n const normalizedSender = sender.toLowerCase();\n const authorizedBots = resolveAuthorizedBots(this.#github.authorizedBots);\n if (authorizedBots.has(normalizedSender)) return true;\n // Any other bot is gated purely by the allowlist: a GitHub App never holds a\n // collaborator permission under its sender login, so falling through to the\n // permission lookup would only fail closed after a wasted API call.\n if (notification.metadata.senderType?.toLowerCase() === 'bot' || normalizedSender.endsWith('[bot]')) {\n return false;\n }\n\n const abortController = new AbortController();\n const timeout = setTimeout(() => abortController.abort(), PERMISSION_CHECK_TIMEOUT_MS);\n try {\n const permission = await this.#github.getRepositoryCollaboratorPermission(\n notification.metadata.installationId,\n repository,\n sender,\n abortController.signal,\n );\n return permission !== undefined && AUTHORIZED_PERMISSIONS.has(permission);\n } catch {\n return false;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\n }\n\n #leaseKey(): string {\n return `${this.name}:${this.#storage.integrationId}`;\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformGithubEventWorkerSettings | null): PlatformGithubEventWorkerSettings {\n if (!value || value.version !== 1 || !value.repositories || typeof value.repositories !== 'object') {\n return { version: 1, repositories: {} };\n }\n return { version: 1, repositories: { ...value.repositories } };\n}\n\n// Events the polling worker forwards to the factory rules engine. Closures\n// let the reconciler finalize cards; `synchronize` and `review_requested` on a\n// pull request are the triggers the review board's re-review path listens for;\n// submitted reviews and pull request comments are how review feedback reaches\n// the agent that authored the branch. Direct-webhook consumers ingest every\n// parsed event; the platform path gates because the remaining events (issue\n// edits, comment edits and deletions) only interest the subscription\n// dispatcher, not the factory rules.\nconst ISSUE_INGESTED_ACTIONS = new Set(['opened', 'reopened', 'edited', 'labeled', 'unlabeled']);\n\nfunction isFactoryIngestedEvent(event: ParsedGithubWebhook): boolean {\n if ((event.event === 'issues' || event.event === 'pull_request') && event.payload.action === 'closed') {\n return true;\n }\n if (event.event === 'pull_request') {\n const action = event.payload.action;\n // `opened` is what mints the Review card for a pull request. Without it a\n // factory-authored PR never gets reviewed on the polling path, which is the\n // only path a local deployment has.\n if (action === 'opened' || action === 'synchronize' || action === 'review_requested') return true;\n }\n // Issue opens, reopens, edits and label changes mint and update Work cards.\n // Without them a new issue never becomes a card on the polling path (#24972).\n if (event.event === 'issues' && ISSUE_INGESTED_ACTIONS.has(String(event.payload.action))) return true;\n if (event.event === 'pull_request_review' && event.payload.action === 'submitted') return true;\n if (event.event === 'issue_comment' && event.payload.action === 'created') return true;\n // Default-branch pushes drive base-checkpoint rebuilds\n // (`withBaseCheckpointWebhookTrigger` wraps the ingest callback).\n if (event.event === 'push') return true;\n return false;\n}\n\nfunction parseEvent(event: EventLogEntry): ParsedGithubWebhook | null {\n if (\n !event.id ||\n !event.deliveryId ||\n !SUPPORTED_EVENTS.has(event.event) ||\n !event.payload ||\n typeof event.payload !== 'object' ||\n Array.isArray(event.payload)\n ) {\n return null;\n }\n return {\n event: event.event,\n deliveryId: event.deliveryId,\n payload: event.payload as Record<string, unknown>,\n };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\n}\n"],"mappings":";;;;;;;AAuBA,MAAM,aAAa;AACnB,MAAM,2BAA2B;AAGjC,MAAM,gCAAgC,KAAK;AAC3C,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,mCAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;CACA;CAGA;AACF,CAAC;AAGD,MAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,yCAAyB,IAAI,IAAgC;CAAC;CAAS;CAAY;AAAO,CAAC;AACjG,MAAM,8BAA8B;AAoDpC,IAAa,4BAAb,cAA+C,aAAa;CAC1D,OAAgB;CAEhB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,cAAuB,WAAW;CAElC,WAAW;CACX;CACA;CACA;CACA,iBAAgC;CAChC;CACA,YAAY;CACZ,aAAa;CAEb,8BAA8B,OAAO;CACrC,wBAAwB,OAAO;CAC/B,YAA+C;EAAE,SAAS;EAAG,cAAc,CAAC;CAAE;CAE9E,YAAY,QAAyC;EACnD,MAAM;EACN,KAAKA,UAAU,OAAO;EACtB,KAAKC,cAAc,OAAO;EAC1B,KAAKC,UAAU,OAAO;EACtB,KAAKC,WAAW,OAAO;EACvB,KAAKC,sBAAsB,OAAO;EAClC,KAAKC,yBAAyB,OAAO;EACrC,KAAKC,+BAA+B,OAAO;EAC3C,KAAKC,qBAAqB,OAAO,qBAAqB;EACtD,MAAM,4BAA4B,OAAO,uBAAuB;EAChE,KAAKC,kCAAk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I,YAAY,MAAM,oBAAoB,GAAK;CAE7D,OAAO;AACT"}
|
|
@@ -65,6 +65,12 @@ export declare class PlatformGithubIntegration implements FactoryIntegration {
|
|
|
65
65
|
repository: string;
|
|
66
66
|
number: number;
|
|
67
67
|
}): Promise<ReconcileIssueState | undefined>;
|
|
68
|
+
listOpenIssueStates(input: {
|
|
69
|
+
installationId: number;
|
|
70
|
+
repository: string;
|
|
71
|
+
}): Promise<Array<ReconcileIssueState & {
|
|
72
|
+
number: number;
|
|
73
|
+
}>>;
|
|
68
74
|
upsertFactoryTriageComment(input: GithubTriageCommentUpsertInput): Promise<GithubTriageCommentUpsertResult>;
|
|
69
75
|
sessionTools({ requestContext }: {
|
|
70
76
|
requestContext: RequestContext;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/github/integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAKxD,OAAO,KAAK,EAEV,MAAM,EAIP,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EAwBV,cAAc,EACf,MAAM,0CAA0C,CAAC;AAClD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,+CAA+C,CAAC;AAC9F,OAAO,KAAK,EAEV,0BAA0B,EAC3B,MAAM,iDAAiD,CAAC;AACzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAC9F,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAE3F,OAAO,KAAK,EACV,iBAAiB,EACjB,0BAA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AAC,eAAe,EAAE,MAAM,GAAG,UAAU,CAAC,iBAAiB,CAAC,wBAAwB,CAAC,CAAC;CAyZzG"}
|
|
@@ -13,6 +13,7 @@ import { registerApiRoute } from "@mastra/core/server";
|
|
|
13
13
|
import { Octokit } from "@octokit/rest";
|
|
14
14
|
//#region src/integrations/platform/github/integration.ts
|
|
15
15
|
const PAGE_SIZE = 30;
|
|
16
|
+
const OPEN_ISSUE_DISCOVERY_MAX_PAGES = 5;
|
|
16
17
|
const API_PREFIX = "/v1/server";
|
|
17
18
|
/**
|
|
18
19
|
* Slug of the GitHub App this integration posts as. Platform credentials do not
|
|
@@ -570,7 +571,7 @@ var PlatformGithubIntegration = class {
|
|
|
570
571
|
storage: ctx.storage.generic,
|
|
571
572
|
ingestFactoryEvent: attachGithubRules(this, ctx),
|
|
572
573
|
reconcileFactoryState: this.#pullRequestReconcileEnabled ? attachGithubReconciler(this, ctx, (input) => this.fetchPullRequestState(input)) : void 0,
|
|
573
|
-
reconcileIssuesFactoryState: this.#issueReconcileEnabled ? attachGithubIssueReconciler(this, ctx, (input) => this.fetchIssueState(input)) : void 0,
|
|
574
|
+
reconcileIssuesFactoryState: this.#issueReconcileEnabled ? attachGithubIssueReconciler(this, ctx, (input) => this.fetchIssueState(input), (input) => this.listOpenIssueStates(input)) : void 0,
|
|
574
575
|
pollEventsEnabled: this.#pollingEnabled,
|
|
575
576
|
intervalMs: this.#pollingIntervalMs,
|
|
576
577
|
pullRequestReconcileIntervalMs: this.#pullRequestReconcileIntervalMs,
|
|
@@ -647,6 +648,30 @@ var PlatformGithubIntegration = class {
|
|
|
647
648
|
return;
|
|
648
649
|
}
|
|
649
650
|
}
|
|
651
|
+
async listOpenIssueStates(input) {
|
|
652
|
+
const issues = [];
|
|
653
|
+
for (let page = 1; page <= OPEN_ISSUE_DISCOVERY_MAX_PAGES; page += 1) {
|
|
654
|
+
const query = new URLSearchParams({
|
|
655
|
+
state: "open",
|
|
656
|
+
page: String(page),
|
|
657
|
+
per_page: String(PAGE_SIZE)
|
|
658
|
+
});
|
|
659
|
+
const result = await this.#client.request("GET", `${repositoryPath(input.repository, "issues")}?${query}`);
|
|
660
|
+
for (const issue of result.issues) issues.push({
|
|
661
|
+
number: issue.number,
|
|
662
|
+
title: issue.title,
|
|
663
|
+
url: issue.htmlUrl,
|
|
664
|
+
state: "open",
|
|
665
|
+
assignees: issue.assignees,
|
|
666
|
+
labels: issue.labels,
|
|
667
|
+
...issue.user?.login ? { author: issue.user.login } : {},
|
|
668
|
+
createdAt: issue.createdAt,
|
|
669
|
+
updatedAt: issue.updatedAt
|
|
670
|
+
});
|
|
671
|
+
if (result.issues.length < PAGE_SIZE) break;
|
|
672
|
+
}
|
|
673
|
+
return issues;
|
|
674
|
+
}
|
|
650
675
|
async upsertFactoryTriageComment(input) {
|
|
651
676
|
const comments = [];
|
|
652
677
|
for (let page = 1;; page += 1) {
|