@mastra/factory 0.18.0 → 0.18.1-alpha.0
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/default-rules.d.ts.map +1 -1
- package/dist/integrations/github/default-rules.js +3 -3
- package/dist/integrations/github/default-rules.js.map +1 -1
- package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/github/reconcile-worker.js +1 -2
- package/dist/integrations/github/reconcile-worker.js.map +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +1 -14
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/gitlab/version-control.d.ts.map +1 -1
- package/dist/integrations/gitlab/version-control.js +4 -5
- package/dist/integrations/gitlab/version-control.js.map +1 -1
- package/dist/integrations/gitlab/webhook.d.ts.map +1 -1
- package/dist/integrations/gitlab/webhook.js +2 -2
- package/dist/integrations/gitlab/webhook.js.map +1 -1
- package/dist/integrations/issue-reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/issue-reconcile-worker.js +1 -2
- package/dist/integrations/issue-reconcile-worker.js.map +1 -1
- package/dist/integrations/linear/integration.d.ts.map +1 -1
- package/dist/integrations/linear/integration.js +10 -30
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +1 -2
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/gitlab/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/gitlab/event-worker.js +1 -2
- package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/linear/event-worker.js +1 -2
- package/dist/integrations/platform/linear/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +9 -9
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/integrations/slack/slack.d.ts.map +1 -1
- package/dist/integrations/slack/slack.js +1 -2
- package/dist/integrations/slack/slack.js.map +1 -1
- package/dist/review-verdict.d.ts +6 -0
- package/dist/review-verdict.d.ts.map +1 -0
- package/dist/review-verdict.js +14 -0
- package/dist/review-verdict.js.map +1 -0
- package/dist/routes/oauth.d.ts.map +1 -1
- package/dist/routes/oauth.js +3 -3
- package/dist/routes/oauth.js.map +1 -1
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +1 -2
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +1 -2
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +5 -5
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +1 -2
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/secret-encryption.js +2 -2
- package/dist/secret-encryption.js.map +1 -1
- package/dist/session/factory-session.d.ts.map +1 -1
- package/dist/session/factory-session.js +1 -2
- package/dist/session/factory-session.js.map +1 -1
- package/dist/session/source-control-tools.d.ts +9 -0
- package/dist/session/source-control-tools.d.ts.map +1 -1
- package/dist/session/source-control-tools.js +51 -2
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/state-signing.js +3 -3
- package/dist/state-signing.js.map +1 -1
- package/dist/storage/domains/audit/base.d.ts.map +1 -1
- package/dist/storage/domains/audit/base.js +2 -3
- package/dist/storage/domains/audit/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +5 -6
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/factory-skills/factory-gitlab-rereview/SKILL.md +1 -1
- package/factory-skills/factory-gitlab-review/SKILL.md +1 -1
- package/factory-skills/factory-rereview/SKILL.md +12 -3
- package/factory-skills/factory-review/SKILL.md +12 -3
- package/package.json +9 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.js","names":["#storage","#projects","#auth","#updateTokens","#inflightRefreshes","#connectionChecks","#orgIdByResourceId","#resolveIntakeDispatch","#listIntakeIssues","#getIntakeIssue","#createIntakeComment","#updateIntakeIssue","#clientId","#clientSecret","#rules","#requestTokens","#listTeamWorkflowStates","#fetchRemainingIssueComments"],"sources":["../../../src/integrations/linear/integration.ts"],"sourcesContent":["/**\n * `LinearIntegration` — the self-contained Linear integration.\n *\n * Implements the system-wide `FactoryIntegration` contract\n * (`../factory-integration.ts`): the deploy entry reads the Linear OAuth env\n * vars ONCE, constructs an instance with explicit credentials, and passes it\n * to `MastraFactory`. Everything Linear-flavored the system does — the OAuth\n * connect/callback flow, workspace/project/issue reads for Intake, and the\n * agent's issue tools — flows through this instance. No other module reads\n * `LINEAR_*` env vars.\n *\n * The class owns:\n * - OAuth: the user-facing authorize URL, code exchange, and refresh-token\n * rotation against Linear's `/oauth/token` endpoint.\n * - GraphQL reads/writes: viewer workspace, projects, active issues for\n * Intake, full issue detail (description + discussion), issue comments.\n * - The HTTP surface (`routes()`) and per-request agent tools\n * (`agentTools()`), delegating to `./routes.ts` / `./agent-tools.ts` with\n * `this` as the API client.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\nimport type { IntegrationConnection } from '../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n ListIntakeIssuesInput,\n UpdateIntakeIssueInput,\n} from '../../capabilities/intake.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntegrationStorageHandle } from '../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { IssueReconcileWorker } from '../issue-reconcile-worker.js';\nimport { buildLinearAgentTools } from './agent-tools.js';\nimport type { LinearEventRules, LinearRuleOverrides } from './default-rules.js';\nimport { resolveLinearRules } from './default-rules.js';\nimport { attachLinearIssueReconciler } from './issue-reconciler.js';\nimport { linearIssueReconciliationEnabled, linearIssueReconciliationInterval } from './reconciliation-config.js';\nimport { buildLinearRoutes } from './routes.js';\nimport { attachLinearRules } from './rules.js';\nimport type { LinearConnectionRow, LinearStorageHandle, UpsertLinearConnectionInput } from './storage.js';\n\nconst LINEAR_GRAPHQL_URL = 'https://api.linear.app/graphql';\nconst LINEAR_TOKEN_URL = 'https://api.linear.app/oauth/token';\nconst LINEAR_AUTHORIZE_URL = 'https://linear.app/oauth/authorize';\n\n/** Credentials and optional event rules for the Linear OAuth application. */\nexport interface LinearIntegrationConfig {\n /** Per-event replacements; omitted events retain defaults, null disables. */\n rules?: LinearRuleOverrides;\n /** OAuth client id of the Linear application. */\n clientId: string;\n /** OAuth client secret of the Linear application. */\n clientSecret: string;\n}\n\n/**\n * Tokens minted by Linear's `/oauth/token` endpoint. Linear access tokens\n * expire (24h) and refresh tokens rotate: every refresh invalidates the old\n * pair, so callers must persist the whole set after each exchange.\n */\nexport interface LinearTokenSet {\n accessToken: string;\n /** Null when Linear issued no refresh token (legacy non-expiring apps). */\n refreshToken: string | null;\n /** Null when Linear reported no `expires_in`. */\n expiresAt: Date | null;\n /** Scopes granted to the token as reported by Linear; null when omitted. */\n scope: string | null;\n}\n\nexport interface LinearWorkspace {\n name: string;\n urlKey: string;\n}\n\nexport interface LinearIssue {\n id: string;\n projectId: string | null;\n /** Backend workspace identity when source ids span multiple workspaces. */\n workspaceId?: string;\n /** Raw Linear team id for exact team-source attribution. */\n teamId: string | null;\n /** Human key like `ENG-123`. */\n identifier: string;\n title: string;\n url: string;\n /** Workflow state name, e.g. `In Progress`. */\n state: string;\n /** Workflow state type, e.g. `backlog` / `unstarted` / `started` / `triage`. */\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the Linear user who created the issue, when Linear returns one. */\n creator: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface LinearIssuePage {\n issues: LinearIssue[];\n /** Opaque cursor for the next page, or `null` on the last page. */\n nextCursor: string | null;\n}\n\nexport interface LinearProjectTeam {\n id: string;\n /** Short team key, e.g. `ENG`. */\n key: string;\n name: string;\n}\n\nexport interface LinearProject {\n id: string;\n name: string;\n /** Project state, e.g. `planned` / `started` / `paused` / `completed`. */\n state: string;\n /** Teams the project belongs to (the Settings picker groups by these). */\n teams: LinearProjectTeam[];\n}\n\n/** A Linear team, selectable as an intake source in its own right. */\nexport interface LinearTeam {\n id: string;\n /** Short team key, e.g. `ENG`. */\n key: string;\n name: string;\n /** Opaque intake source identifier. Optional on the wire for compatibility. */\n sourceId?: string;\n}\n\nexport interface LinearIssueComment {\n author: string | null;\n body: string;\n createdAt: string;\n}\n\n/** Full issue payload for agent context: everything in {@link LinearIssue} plus description and discussion. */\nexport interface LinearIssueDetail extends LinearIssue {\n /** Markdown body of the issue, or `null` when empty. */\n description: string | null;\n /** Discussion comments, oldest first. */\n comments: LinearIssueComment[];\n}\n\n/** The comment created by {@link LinearIntegration.createIssueComment}. */\nexport interface LinearCreatedComment {\n id: string;\n url: string;\n}\n\nconst LINEAR_ISSUES_PAGE_SIZE = 30;\nconst ISSUE_COMMENTS_PAGE_SIZE = 50;\nconst LINEAR_TEAMS_PAGE_SIZE = 100;\nconst LINEAR_TEAMS_MAX_PAGES = 20;\n/** Hard stop for comment pagination so a misbehaving cursor can't loop forever. */\nconst ISSUE_COMMENTS_MAX_PAGES = 20;\n\n/** Refresh this many ms before the recorded expiry to absorb clock skew. */\nconst TOKEN_REFRESH_SKEW_MS = 60_000;\n\n/** Re-check an org's Linear connection (and its scopes) at most this often. */\nconst CONNECTION_TTL_MS = 60_000;\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Thrown when the org's Linear authorization can no longer be renewed. */\nexport class LinearReauthRequiredError extends Error {\n constructor() {\n super('Linear authorization expired. Reconnect Linear to keep syncing intake issues.');\n }\n}\n\n/** Cached result of {@link LinearIntegration.checkConnection}. */\nexport interface LinearConnectionCheck {\n connected: boolean;\n /** Whether the granted OAuth scope allows posting issue comments. */\n canComment: boolean;\n checkedAt: number;\n}\n\ninterface IssuesQueryData {\n issues: {\n nodes: Array<{\n id: string;\n identifier: string;\n title: string;\n url: string;\n priorityLabel: string;\n createdAt: string;\n updatedAt: string;\n state: { name: string; type: string };\n project: { id: string } | null;\n assignee: { name: string } | null;\n creator: { name: string } | null;\n team: { id: string; key: string } | null;\n labels: { nodes: Array<{ name: string }> };\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n}\n\ninterface IssueCommentNode {\n body: string;\n createdAt: string;\n user: { name: string } | null;\n}\n\ninterface IssueCommentsPage {\n nodes: IssueCommentNode[];\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n}\n\ninterface IssueDetailQueryData {\n issue: {\n id: string;\n identifier: string;\n title: string;\n description: string | null;\n url: string;\n priorityLabel: string;\n createdAt: string;\n updatedAt: string;\n state: { name: string; type: string };\n project: { id: string } | null;\n assignee: { name: string } | null;\n creator: { name: string } | null;\n team: { id: string; key: string } | null;\n labels: { nodes: Array<{ name: string }> };\n comments: IssueCommentsPage;\n } | null;\n}\n\ninterface IssueCommentsQueryData {\n issue: { comments: IssueCommentsPage } | null;\n}\n\ninterface IssueIdQueryData {\n issue: { id: string } | null;\n}\n\ninterface CommentCreateMutationData {\n commentCreate: { success: boolean; comment: { id: string; url: string } | null };\n}\n\n/** POST a GraphQL query to Linear with the given OAuth access token. */\nasync function linearGraphql<T>(accessToken: string, query: string, variables?: Record<string, unknown>): Promise<T> {\n const res = await fetch(LINEAR_GRAPHQL_URL, {\n method: 'POST',\n signal: AbortSignal.timeout(15_000),\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({ query, variables }),\n });\n if (!res.ok) {\n // Linear returns GraphQL errors (validation, missing scopes, …) with a\n // 400 status — surface the actual message instead of just the code.\n let detail: string | null = null;\n try {\n const errBody = (await res.json()) as { errors?: Array<{ message?: string }> };\n detail = errBody.errors?.[0]?.message ?? null;\n } catch {\n // Non-JSON error body; fall back to the status code alone.\n }\n const err = new Error(`Linear API request failed (${res.status})${detail ? `: ${detail}` : ''}`);\n (err as { status?: number }).status = res.status;\n throw err;\n }\n const body = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };\n if (body.errors?.length) {\n throw new Error(`Linear API error: ${body.errors[0]?.message ?? 'unknown error'}`);\n }\n if (!body.data) {\n throw new Error('Linear API returned no data.');\n }\n return body.data;\n}\n\nexport class LinearIntegration implements FactoryIntegration {\n /** Stable integration identifier (see `../base.ts`). */\n readonly id = 'linear';\n /** Bound once by the factory via `initialize()` before any surface is used. */\n #storage: LinearStorageHandle | undefined;\n #projects: FactoryProjectsStorage | undefined;\n #auth: RouteAuth | undefined;\n\n /** Bind Linear's slice of the generic integration storage, the projects domain, and the host auth seam. */\n initialize({\n storage,\n projects,\n auth,\n }: {\n storage: IntegrationStorageHandle;\n projects: FactoryProjectsStorage;\n auth: RouteAuth;\n }): void {\n this.#storage = storage as unknown as LinearStorageHandle;\n this.#projects = projects;\n this.#auth = auth;\n }\n\n get storage(): LinearStorageHandle {\n if (!this.#storage) {\n throw new Error('LinearIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#storage;\n }\n\n /** Factory projects domain — maps a session's resourceId to its owning org. */\n get projects(): FactoryProjectsStorage {\n if (!this.#projects) {\n throw new Error('LinearIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#projects;\n }\n\n /**\n * Whether the host runs with web auth enabled. Linear connections are\n * org-owned, so every Linear surface is inert without a tenant auth seam.\n */\n get authEnabled(): boolean {\n return this.#auth?.enabled() ?? false;\n }\n\n // ── Connection + OAuth token lifecycle ───────────────────────────────────\n\n /** Load the org's Linear connection, or `null` when not connected. */\n async loadConnection(orgId: string): Promise<LinearConnectionRow | null> {\n const connection = await this.storage.connections.get(orgId);\n if (!connection) return null;\n const { data } = connection;\n return {\n id: connection.id,\n orgId: connection.orgId,\n userId: connection.userId,\n accessToken: data.accessToken,\n scope: data.scope ?? null,\n refreshToken: data.refreshToken ?? null,\n expiresAt: data.expiresAtMs === null || data.expiresAtMs === undefined ? null : new Date(data.expiresAtMs),\n workspaceName: data.workspaceName ?? null,\n workspaceUrlKey: data.workspaceUrlKey ?? null,\n createdAt: connection.createdAt,\n updatedAt: connection.updatedAt,\n };\n }\n\n /** Insert or replace the org's connection (one per org). */\n async upsertConnection(input: UpsertLinearConnectionInput): Promise<void> {\n await this.storage.connections.upsert(input.orgId, {\n userId: input.userId,\n data: {\n accessToken: input.accessToken,\n refreshToken: input.refreshToken,\n expiresAtMs: input.expiresAt?.getTime() ?? null,\n scope: input.scope,\n workspaceName: input.workspaceName,\n workspaceUrlKey: input.workspaceUrlKey,\n },\n });\n // Let the agent tools see the new connection immediately.\n this.invalidateConnectionCache(input.orgId);\n }\n\n /** Persist a rotated token set on the org's existing connection row. */\n async #updateTokens(orgId: string, tokens: LinearTokenSet): Promise<void> {\n await this.storage.connections.update(orgId, data => ({\n ...data,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAtMs: tokens.expiresAt?.getTime() ?? null,\n // Refresh responses may omit scope; keep the recorded grant.\n scope: tokens.scope ?? data.scope,\n }));\n }\n\n /**\n * Whether the connection's token can post issue comments. Legacy rows\n * without a recorded scope were minted with `read` only, so they count as\n * read-only until the org reconnects Linear.\n */\n canPostComments(connection: LinearConnectionRow): boolean {\n const scopes = (connection.scope ?? '').split(/[\\s,]+/).filter(Boolean);\n return scopes.some(scope => scope === 'comments:create' || scope === 'write' || scope === 'admin');\n }\n\n /**\n * In-flight refreshes keyed by org. Linear rotates refresh tokens, so two\n * concurrent refreshes with the same token would invalidate each other —\n * single-flight ensures one exchange per org and shares the result.\n */\n readonly #inflightRefreshes = new Map<string, Promise<string>>();\n\n /**\n * Return a usable access token for the connection, proactively refreshing\n * it when the recorded expiry is past (or imminent). Throws\n * `LinearReauthRequiredError` when the token is expired and cannot be\n * refreshed — the org has to go through the OAuth flow again.\n */\n async getFreshAccessToken(connection: LinearConnectionRow): Promise<string> {\n const expired =\n connection.expiresAt !== null && connection.expiresAt.getTime() - TOKEN_REFRESH_SKEW_MS <= Date.now();\n if (!expired) return connection.accessToken;\n\n if (!connection.refreshToken) {\n // Legacy row from before refresh-token support: nothing to renew with.\n throw new LinearReauthRequiredError();\n }\n\n const existing = this.#inflightRefreshes.get(connection.orgId);\n if (existing) return existing;\n\n // The caller may hold a stale row: another request could have refreshed\n // and rotated the refresh token since this row was loaded. Reload before\n // refreshing so we don't burn the rotated token and force a false reauth.\n const latest = await this.loadConnection(connection.orgId);\n if (!latest) throw new LinearReauthRequiredError();\n\n const concurrent = this.#inflightRefreshes.get(connection.orgId);\n if (concurrent) return concurrent;\n\n const latestExpired = latest.expiresAt !== null && latest.expiresAt.getTime() - TOKEN_REFRESH_SKEW_MS <= Date.now();\n if (!latestExpired) return latest.accessToken;\n if (!latest.refreshToken) throw new LinearReauthRequiredError();\n\n const refreshToken = latest.refreshToken;\n const refresh = (async () => {\n try {\n const tokens = await this.refreshAccessToken(refreshToken);\n await this.#updateTokens(connection.orgId, tokens);\n return tokens.accessToken;\n } catch (err) {\n const status = (err as { status?: number }).status;\n // invalid_grant surfaces as 400/401: the refresh token was revoked or\n // already rotated away. Terminal for this connection.\n if (status === 400 || status === 401) throw new LinearReauthRequiredError();\n throw err;\n } finally {\n this.#inflightRefreshes.delete(connection.orgId);\n }\n })();\n this.#inflightRefreshes.set(connection.orgId, refresh);\n return refresh;\n }\n\n // ── Connection checks for agent tools ────────────────────────────────────\n\n /** Re-check an org's Linear connection (and its scopes) at most this often. */\n readonly #connectionChecks = new Map<string, LinearConnectionCheck>();\n\n /**\n * Whether the org has an active connection and whether its granted scope\n * allows posting comments. Cached per org with a short TTL — tool-set\n * resolution runs on every request.\n */\n async checkConnection(orgId: string): Promise<LinearConnectionCheck> {\n const cached = this.#connectionChecks.get(orgId);\n if (cached && Date.now() - cached.checkedAt < CONNECTION_TTL_MS) return cached;\n const connection = await this.loadConnection(orgId);\n const check: LinearConnectionCheck = {\n connected: connection !== null,\n canComment: connection !== null && this.canPostComments(connection),\n checkedAt: Date.now(),\n };\n this.#connectionChecks.set(orgId, check);\n return check;\n }\n\n /**\n * Drop the cached connection check for an org. Called after a connection is\n * persisted so the tools show up on the very next run instead of after the\n * TTL lapses.\n */\n invalidateConnectionCache(orgId: string): void {\n this.#connectionChecks.delete(orgId);\n }\n\n /**\n * A project's org never changes, so the resourceId → orgId mapping is\n * cached forever. `null` marks resource ids that aren't factory projects\n * (e.g. local default resources) so we don't re-query them on every\n * tool-set resolution.\n */\n readonly #orgIdByResourceId = new Map<string, string | null>();\n\n /** Map a session's resourceId to its owning org, or `null` when it isn't a project. */\n async resolveOrgId(resourceId: string): Promise<string | null> {\n const cached = this.#orgIdByResourceId.get(resourceId);\n if (cached !== undefined) return cached;\n // Non-UUID resource ids (local/dev resources) would make the uuid column\n // comparison throw — they're definitively \"not a project\", so cache that.\n if (!UUID_PATTERN.test(resourceId)) {\n this.#orgIdByResourceId.set(resourceId, null);\n return null;\n }\n let orgId: string | null;\n try {\n await this.projects.ensureReady();\n const project = await this.projects.getById({ id: resourceId });\n orgId = project?.orgId ?? null;\n } catch {\n // Transient database failure: skip the tools for this request but don't\n // cache the miss, so the next request retries the lookup.\n return null;\n }\n this.#orgIdByResourceId.set(resourceId, orgId);\n return orgId;\n }\n\n /** Test hook: clear the org/connection caches between specs. */\n clearCaches(): void {\n this.#orgIdByResourceId.clear();\n this.#connectionChecks.clear();\n }\n\n readonly intake: Intake = {\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: async ({ orgId }) => {\n const connection = await this.loadConnection(orgId);\n if (!connection) return [];\n const accessToken = await this.getFreshAccessToken(connection);\n const [projects, teams] = await Promise.all([this.listProjects(accessToken), this.listTeams(accessToken)]);\n return [\n ...projects.map(project => ({\n id: project.id,\n name: project.name,\n type: 'project' as const,\n })),\n ...teams.map(team => ({\n id: encodeSelfManagedTeamSourceId(team.id),\n name: team.name,\n type: 'team' as const,\n metadata: { teamKey: team.key },\n })),\n ];\n },\n listItems: async ({ orgId, sourceIds, attributionSourceIds, cursor }) => {\n if (sourceIds.length === 0) return { items: [], nextCursor: null };\n const connection = await this.loadConnection(orgId);\n if (!connection) return { items: [], nextCursor: null };\n const accessToken = await this.getFreshAccessToken(connection);\n const page = await this.#listIntakeIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds,\n attributionSourceIds,\n cursor,\n });\n return {\n items: page.issues.flatMap(issue => {\n if (!issue.sourceId) return [];\n return [\n {\n source: { type: 'issue', externalId: issue.id, url: issue.url },\n sourceId: issue.sourceId,\n title: `${issue.identifier}: ${issue.title}`,\n status: issue.state ?? '',\n labels: issue.labels,\n assignee: issue.assignee,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n metadata: {\n identifier: issue.identifier,\n ...(issue.projectId ? { linearProjectId: issue.projectId } : {}),\n stateType: issue.stateType,\n priority: issue.priority,\n team: issue.source,\n },\n },\n ];\n }),\n nextCursor: page.nextCursor,\n };\n },\n listIssues: input => this.#listIntakeIssues(input),\n getIssue: input => this.#getIntakeIssue(input),\n createComment: input => this.#createIntakeComment(input),\n updateIssue: input => this.#updateIntakeIssue(input),\n };\n\n /**\n * Background-dispatch context: the org's OAuth connection with a fresh\n * token. Linear work items store the issue UUID directly as `externalId`.\n */\n async #resolveIntakeDispatch({\n orgId,\n externalSource,\n }: {\n orgId: string;\n externalSource: { type: string; externalId: string };\n }): Promise<{ connection: IntegrationConnection; issueId: string } | null> {\n if (externalSource.type !== 'issue') return null;\n const connection = await this.loadConnection(orgId);\n if (!connection) return null;\n const accessToken = await this.getFreshAccessToken(connection);\n return { connection: { type: 'oauth', accessToken }, issueId: externalSource.externalId };\n }\n /**\n * The OAuth connect/callback flow round-trips a signed `state` through\n * Linear, so a multi-replica deploy needs a deployment-stable state secret.\n */\n readonly requiresStableStateSigner = true;\n\n readonly #clientId: string;\n readonly #clientSecret: string;\n\n readonly #rules: LinearEventRules;\n\n get rules(): LinearEventRules {\n return this.#rules;\n }\n\n constructor(config: LinearIntegrationConfig) {\n this.#rules = resolveLinearRules(config.rules);\n const missing = (['clientId', 'clientSecret'] as const).filter(key => !config[key]);\n if (missing.length > 0) {\n throw new Error(`LinearIntegration is missing required config: ${missing.join(', ')}.`);\n }\n this.#clientId = config.clientId;\n this.#clientSecret = config.clientSecret;\n }\n\n // ── OAuth ────────────────────────────────────────────────────────────────\n\n /**\n * Build the OAuth authorize URL. `prompt=consent` forces the workspace\n * picker even for an already-authorized user, so \"reconnect\" can switch\n * workspaces.\n */\n buildAuthorizeUrl(state: string, redirectUri: string): string {\n const url = new URL(LINEAR_AUTHORIZE_URL);\n url.searchParams.set('client_id', this.#clientId);\n url.searchParams.set('redirect_uri', redirectUri);\n url.searchParams.set('response_type', 'code');\n // `comments:create` lets the agent's linear_create_comment tool post\n // comments; everything else the integration does is read-only.\n url.searchParams.set('scope', 'read,comments:create');\n url.searchParams.set('state', state);\n url.searchParams.set('prompt', 'consent');\n return url.toString();\n }\n\n /** Exchange an OAuth `code` for a workspace-scoped token set. */\n async exchangeOAuthCode(code: string, redirectUri: string): Promise<LinearTokenSet> {\n return this.#requestTokens({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }, 'token exchange');\n }\n\n /**\n * Exchange a refresh token for a new token set. Linear rotates refresh\n * tokens, so the returned set replaces the stored one entirely. A 400/401\n * here means the refresh token is invalid/revoked and the org must\n * re-authorize.\n */\n async refreshAccessToken(refreshToken: string): Promise<LinearTokenSet> {\n return this.#requestTokens({ grant_type: 'refresh_token', refresh_token: refreshToken }, 'token refresh');\n }\n\n /** POST to Linear's token endpoint and normalize the response. */\n async #requestTokens(params: Record<string, string>, label: string): Promise<LinearTokenSet> {\n const res = await fetch(LINEAR_TOKEN_URL, {\n method: 'POST',\n signal: AbortSignal.timeout(10_000),\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n ...params,\n client_id: this.#clientId,\n client_secret: this.#clientSecret,\n }),\n });\n if (!res.ok) {\n const err = new Error(`Linear ${label} failed (${res.status})`);\n (err as { status?: number }).status = res.status;\n throw err;\n }\n const body = (await res.json()) as {\n access_token?: string;\n refresh_token?: string;\n expires_in?: number;\n scope?: string;\n };\n if (!body.access_token) {\n throw new Error(`Linear ${label} returned no access token.`);\n }\n return {\n accessToken: body.access_token,\n refreshToken: body.refresh_token ?? null,\n expiresAt: typeof body.expires_in === 'number' ? new Date(Date.now() + body.expires_in * 1000) : null,\n scope: body.scope ?? null,\n };\n }\n\n // ── GraphQL reads/writes ─────────────────────────────────────────────────\n\n /** Fetch the workspace (organization) the access token is scoped to. */\n async fetchWorkspace(accessToken: string): Promise<LinearWorkspace> {\n const data = await linearGraphql<{ organization: { name: string; urlKey: string } }>(\n accessToken,\n `query { organization { name urlKey } }`,\n );\n return { name: data.organization.name, urlKey: data.organization.urlKey };\n }\n\n async #listIntakeIssues(input: ListIntakeIssuesInput): Promise<{ issues: IntakeIssue[]; nextCursor: string | null }> {\n const accessToken = getLinearAccessToken(input.connection);\n if (input.sourceIds.length === 0) return { issues: [], nextCursor: null };\n const attributionSourceIds = input.attributionSourceIds ?? input.sourceIds;\n const { projectIds, teamIds } = splitSelfManagedSourceIds(input.sourceIds);\n const cursors = decodeSelfManagedListCursor(input.cursor, input.sourceIds, attributionSourceIds);\n\n // Project-only intake still uses one Linear query, but its provider cursor\n // is wrapped so a later source-selection change cannot reinterpret it.\n if (teamIds.length === 0) {\n if (cursors.projects === null) return { issues: [], nextCursor: null };\n const result = await this.listActiveIssues(accessToken, cursors.projects, projectIds, input.labels);\n return {\n issues: result.issues.map(issue => linearIssueToIntakeIssue(issue)),\n nextCursor: encodeSelfManagedListCursor(\n { projects: result.nextCursor, teams: null },\n input.sourceIds,\n attributionSourceIds,\n ),\n };\n }\n\n // A team is selected. List projects and teams separately (the two Linear\n // filters would AND together in one query) and stamp each issue with the\n // selected source that surfaced it. Each source kind paginates on its own\n // cursor, carried in a compound cursor when both are present.\n const projectResult =\n projectIds.length > 0 && cursors.projects !== null\n ? await this.listActiveIssues(accessToken, cursors.projects, projectIds, input.labels)\n : { issues: [], nextCursor: null };\n const teamResult =\n cursors.teams !== null\n ? await this.listActiveIssues(accessToken, cursors.teams, undefined, input.labels, teamIds)\n : { issues: [], nextCursor: null };\n\n // Stamp project issues with their (selected) project id; stamp team issues\n // with the team source id. A team issue whose project was also selected is\n // reconciled by the dedupe step below (project wins).\n const projectIssues = projectResult.issues.map(issue => linearIssueToIntakeIssue(issue));\n const selectedTeamSourceById = new Map(teamIds.map(teamId => [teamId, encodeSelfManagedTeamSourceId(teamId)]));\n const selectedProjectIds = new Set(splitSelfManagedSourceIds(attributionSourceIds).projectIds);\n const teamIssues = teamResult.issues\n .filter(issue => issue.projectId === null || !selectedProjectIds.has(issue.projectId))\n .map(issue => {\n const teamSourceId = issue.teamId ? selectedTeamSourceById.get(issue.teamId) : undefined;\n if (!teamSourceId) throw new Error('Linear returned an issue outside the selected teams.');\n return { ...linearIssueToIntakeIssue(issue), sourceId: teamSourceId };\n });\n\n const deduped = dedupeSelfManagedIssues([...projectIssues, ...teamIssues]);\n return {\n issues: deduped,\n nextCursor: encodeSelfManagedListCursor(\n { projects: projectResult.nextCursor, teams: teamResult.nextCursor },\n input.sourceIds,\n attributionSourceIds,\n ),\n };\n }\n\n async #getIntakeIssue(input: GetIntakeIssueInput): Promise<IntakeIssueDetail | null> {\n const accessToken = getLinearAccessToken(input.connection);\n const issue = await this.fetchIssueDetail(accessToken, input.issueId);\n if (!issue) return null;\n return {\n ...linearIssueToIntakeIssue(issue),\n description: issue.description,\n commentCount: issue.comments.length,\n comments: issue.comments,\n };\n }\n\n async #createIntakeComment(input: CreateIntakeCommentInput): Promise<{ id: string; url: string } | null> {\n const accessToken = getLinearAccessToken(input.connection);\n return this.createIssueComment(accessToken, input.issueId, input.body);\n }\n\n async #updateIntakeIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> {\n const accessToken = getLinearAccessToken(input.connection);\n const issue = await this.fetchIssueDetail(accessToken, input.issueId);\n if (!issue) return null;\n const teamKey = issue.team;\n if (!teamKey) return null;\n const states = await this.#listTeamWorkflowStates(accessToken, teamKey);\n let targetState: { id: string; name: string; type: string } | null = null;\n if (input.state.kind === 'byType') {\n const wantedType = input.state.stateType;\n targetState = states.find(state => state.type === wantedType) ?? null;\n } else {\n const wanted = input.state.name.toLowerCase();\n targetState = states.find(state => state.name.toLowerCase() === wanted) ?? null;\n }\n if (!targetState) return null;\n if (targetState.name === issue.state) {\n return linearIssueToIntakeIssue(issue);\n }\n const data = await linearGraphql<{ issueUpdate: { success: boolean } }>(\n accessToken,\n `mutation UpdateIssueState($id: String!, $stateId: String!) {\n issueUpdate(id: $id, input: { stateId: $stateId }) { success }\n }`,\n { id: issue.id, stateId: targetState.id },\n );\n if (!data.issueUpdate.success) {\n throw new Error('Linear did not accept the issue update.');\n }\n const fresh = await this.fetchIssueDetail(accessToken, issue.id);\n if (!fresh) return null;\n return linearIssueToIntakeIssue(fresh);\n }\n\n async #listTeamWorkflowStates(\n accessToken: string,\n teamKey: string,\n ): Promise<Array<{ id: string; name: string; type: string }>> {\n const data = await linearGraphql<{\n team: { states: { nodes: Array<{ id: string; name: string; type: string }> } } | null;\n }>(\n accessToken,\n `query TeamStates($key: String!) {\n team(id: $key) { states(first: 100) { nodes { id name type } } }\n }`,\n { key: teamKey },\n );\n return data.team?.states.nodes ?? [];\n }\n\n /** List the workspace's projects (for the Settings intake-source picker). */\n async listProjects(accessToken: string): Promise<LinearProject[]> {\n const data = await linearGraphql<{\n projects: {\n nodes: Array<{\n id: string;\n name: string;\n state: string;\n teams: { nodes: Array<{ id: string; key: string; name: string }> };\n }>;\n };\n }>(\n accessToken,\n `query { projects(first: 100) { nodes { id name state teams(first: 10) { nodes { id key name } } } } }`,\n );\n return data.projects.nodes.map(node => ({\n id: node.id,\n name: node.name,\n state: node.state,\n teams: node.teams.nodes.map(team => ({ id: team.id, key: team.key, name: team.name })),\n }));\n }\n\n /** List the workspace's teams (for the Settings intake-source picker). */\n async listTeams(accessToken: string): Promise<LinearTeam[]> {\n const teams: Array<{ id: string; key: string; name: string }> = [];\n let after: string | undefined;\n for (let page = 0; page < LINEAR_TEAMS_MAX_PAGES; page += 1) {\n const data = await linearGraphql<{\n teams: {\n nodes: Array<{ id: string; key: string; name: string }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n }>(\n accessToken,\n `query Teams($first: Int!, $after: String) {\n teams(first: $first, after: $after) {\n nodes { id key name }\n pageInfo { hasNextPage endCursor }\n }\n }`,\n { first: LINEAR_TEAMS_PAGE_SIZE, ...(after ? { after } : {}) },\n );\n teams.push(...data.teams.nodes);\n if (!data.teams.pageInfo.hasNextPage || !data.teams.pageInfo.endCursor) break;\n // A page that hands back the cursor it was asked for would replay forever.\n if (data.teams.pageInfo.endCursor === after) throw invalidLinearCursor();\n after = data.teams.pageInfo.endCursor;\n }\n return teams.map(team => ({\n id: team.id,\n key: team.key,\n name: team.name,\n sourceId: encodeSelfManagedTeamSourceId(team.id),\n }));\n }\n\n sourceMatchesIssue(sourceId: string, issue: Pick<LinearIssueDetail, 'projectId' | 'teamId'>): boolean {\n return isSelfManagedTeamSourceId(sourceId)\n ? issue.teamId === decodeSelfManagedTeamSourceId(sourceId)\n : issue.projectId === sourceId;\n }\n\n /**\n * List one page of the workspace's active issues (triage/backlog/unstarted/\n * started — completed and canceled are excluded), most recently updated\n * first. When `projectIds` is provided, only issues from those projects are\n * returned. When `teamIds` is provided, only issues in those teams are\n * returned, including issues that belong to no project. Callers list team\n * sources and project sources in separate calls so the two filters are not\n * AND-ed together.\n */\n async listActiveIssues(\n accessToken: string,\n after?: string,\n projectIds?: string[],\n labels?: string[],\n teamIds?: string[],\n ): Promise<LinearIssuePage> {\n const normalizedLabels = [...new Set((labels ?? []).map(label => label.trim()).filter(Boolean))];\n const projectFilter = projectIds?.length ? ', project: { id: { in: $projectIds } }' : '';\n const projectVar = projectIds?.length ? ', $projectIds: [ID!]' : '';\n const teamFilter = teamIds?.length ? ', team: { id: { in: $teamIds } }' : '';\n const teamVar = teamIds?.length ? ', $teamIds: [ID!]' : '';\n const labelFilter = normalizedLabels.length > 0 ? ', labels: { name: { in: $labels } }' : '';\n const labelVar = normalizedLabels.length > 0 ? ', $labels: [String!]' : '';\n const data = await linearGraphql<IssuesQueryData>(\n accessToken,\n `query Intake($first: Int!, $after: String${projectVar}${teamVar}${labelVar}) {\n issues(\n first: $first\n after: $after\n orderBy: updatedAt\n filter: { state: { type: { in: [\"triage\", \"backlog\", \"unstarted\", \"started\"] } }${projectFilter}${teamFilter}${labelFilter} }\n ) {\n nodes {\n id\n identifier\n title\n url\n priorityLabel\n createdAt\n updatedAt\n state { name type }\n project { id }\n assignee { name }\n creator { name }\n team { id key }\n labels { nodes { name } }\n }\n pageInfo { hasNextPage endCursor }\n }\n }`,\n {\n first: LINEAR_ISSUES_PAGE_SIZE,\n after: after ?? null,\n ...(projectIds?.length ? { projectIds } : {}),\n ...(teamIds?.length ? { teamIds } : {}),\n ...(normalizedLabels.length > 0 ? { labels: normalizedLabels } : {}),\n },\n );\n const { nodes, pageInfo } = data.issues;\n return {\n issues: nodes.map(node => ({\n id: node.id,\n projectId: node.project?.id ?? null,\n identifier: node.identifier,\n title: node.title,\n url: node.url,\n state: node.state.name,\n stateType: node.state.type,\n priorityLabel: node.priorityLabel,\n assignee: node.assignee?.name ?? null,\n creator: node.creator?.name ?? null,\n team: node.team?.key ?? null,\n labels: node.labels.nodes.map(label => label.name),\n createdAt: node.createdAt,\n updatedAt: node.updatedAt,\n teamId: node.team?.id ?? null,\n })),\n nextCursor: pageInfo.hasNextPage ? pageInfo.endCursor : null,\n };\n }\n\n /** Follow `comments.pageInfo` until exhausted so long discussions aren't truncated. */\n async #fetchRemainingIssueComments(\n accessToken: string,\n issueId: string,\n firstPage: IssueCommentsPage,\n ): Promise<IssueCommentNode[]> {\n const nodes = [...firstPage.nodes];\n let { hasNextPage, endCursor } = firstPage.pageInfo;\n for (let page = 1; hasNextPage && endCursor && page < ISSUE_COMMENTS_MAX_PAGES; page++) {\n const data = await linearGraphql<IssueCommentsQueryData>(\n accessToken,\n `query IssueComments($id: String!, $first: Int!, $after: String!) {\n issue(id: $id) {\n comments(first: $first, after: $after) {\n nodes { body createdAt user { name } }\n pageInfo { hasNextPage endCursor }\n }\n }\n }`,\n { id: issueId, first: ISSUE_COMMENTS_PAGE_SIZE, after: endCursor },\n );\n const comments = data.issue?.comments;\n if (!comments) break;\n nodes.push(...comments.nodes);\n if (comments.pageInfo.hasNextPage && comments.pageInfo.endCursor === endCursor) throw invalidLinearCursor();\n ({ hasNextPage, endCursor } = comments.pageInfo);\n }\n return nodes;\n }\n\n /**\n * Fetch one issue with its description and comments. `idOrIdentifier`\n * accepts both the Linear UUID and the human key (`ENG-123`). Returns\n * `null` when the issue doesn't exist (Linear reports it as an \"Entity not\n * found\" error).\n */\n async fetchIssueDetail(\n accessToken: string,\n idOrIdentifier: string,\n _sourceIds?: string[],\n _routedSourceIds?: string[],\n ): Promise<LinearIssueDetail | null> {\n let data: IssueDetailQueryData;\n try {\n data = await linearGraphql<IssueDetailQueryData>(\n accessToken,\n `query IssueDetail($id: String!, $commentsFirst: Int!) {\n issue(id: $id) {\n id\n identifier\n title\n description\n url\n priorityLabel\n createdAt\n updatedAt\n state { name type }\n project { id }\n assignee { name }\n creator { name }\n team { id key }\n labels { nodes { name } }\n comments(first: $commentsFirst) {\n nodes { body createdAt user { name } }\n pageInfo { hasNextPage endCursor }\n }\n }\n }`,\n { id: idOrIdentifier, commentsFirst: ISSUE_COMMENTS_PAGE_SIZE },\n );\n } catch (err) {\n // Linear surfaces unknown ids/identifiers as a GraphQL \"Entity not\n // found\" error rather than a null node — map that to \"issue doesn't\n // exist\".\n if (err instanceof Error && /entity not found/i.test(err.message)) return null;\n throw err;\n }\n const issue = data.issue;\n if (!issue) return null;\n const allComments = await this.#fetchRemainingIssueComments(accessToken, issue.id, issue.comments);\n const comments = allComments.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());\n return {\n id: issue.id,\n projectId: issue.project?.id ?? null,\n teamId: issue.team?.id ?? null,\n identifier: issue.identifier,\n title: issue.title,\n description: issue.description?.trim() ? issue.description : null,\n url: issue.url,\n state: issue.state.name,\n stateType: issue.state.type,\n priorityLabel: issue.priorityLabel,\n assignee: issue.assignee?.name ?? null,\n creator: issue.creator?.name ?? null,\n team: issue.team?.key ?? null,\n labels: issue.labels.nodes.map(label => label.name),\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n comments: comments.map(comment => ({\n author: comment.user?.name ?? null,\n body: comment.body,\n createdAt: comment.createdAt,\n })),\n };\n }\n\n /**\n * Post a comment on an issue. `idOrIdentifier` accepts both the Linear UUID\n * and the human key (`ENG-123`) — the identifier is resolved to a UUID\n * first because `commentCreate` only accepts UUIDs. Returns `null` when the\n * issue doesn't exist.\n */\n async createIssueComment(\n accessToken: string,\n idOrIdentifier: string,\n body: string,\n ): Promise<LinearCreatedComment | null> {\n let issueId: string;\n try {\n const data = await linearGraphql<IssueIdQueryData>(\n accessToken,\n `query IssueId($id: String!) { issue(id: $id) { id } }`,\n { id: idOrIdentifier },\n );\n if (!data.issue) return null;\n issueId = data.issue.id;\n } catch (err) {\n if (err instanceof Error && /entity not found/i.test(err.message)) return null;\n throw err;\n }\n const data = await linearGraphql<CommentCreateMutationData>(\n accessToken,\n `mutation CommentCreate($input: CommentCreateInput!) {\n commentCreate(input: $input) { success comment { id url } }\n }`,\n { input: { issueId, body } },\n );\n if (!data.commentCreate.success || !data.commentCreate.comment) {\n throw new Error('Linear did not accept the comment.');\n }\n return data.commentCreate.comment;\n }\n\n // ── FactoryIntegration surface ───────────────────────────────────────────\n\n workers(ctx: IntegrationContext): MastraWorker[] {\n if (!linearIssueReconciliationEnabled()) return [];\n const reconcile = attachLinearIssueReconciler(this, ctx);\n if (!reconcile) return [];\n const intervalMs = linearIssueReconciliationInterval();\n return [\n new IssueReconcileWorker({\n integrationId: this.id,\n reconcile,\n ...(intervalMs ? { intervalMs } : {}),\n }),\n ];\n }\n\n /**\n * The integration's HTTP surface: `/web/linear/*` + `/auth/linear/*` Mastra\n * `apiRoutes` (status, OAuth connect/callback, projects + issues for\n * Intake). Handlers operate on this instance.\n */\n routes(ctx: IntegrationContext): ApiRoute[] {\n return buildLinearRoutes({\n linear: this,\n auth: ctx.auth,\n stateSigner: ctx.stateSigner,\n baseUrl: ctx.baseUrl,\n intake: ctx.storage.intake,\n projects: ctx.storage.projects,\n ingestFactoryIssues: attachLinearRules(this, ctx),\n workItems: ctx.runtime?.workItems,\n boards: ctx.runtime?.boards,\n });\n }\n\n /**\n * Org-scoped agent tools: issue detail + comment tools for sessions whose\n * project belongs to an org with an active Linear connection.\n */\n async agentTools(args: { requestContext: RequestContext }): Promise<IntegrationTools> {\n return buildLinearAgentTools({ requestContext: args.requestContext, linear: this });\n }\n\n /** Non-secret config snapshot for system diagnostics/startup logs. */\n diagnostics(): Record<string, unknown> {\n return {\n oauthAppConfigured: true,\n };\n }\n}\n\nfunction getLinearAccessToken(connection: IntegrationConnection): string {\n if (connection.type !== 'oauth') {\n throw new Error('Linear capabilities require an OAuth connection.');\n }\n return connection.accessToken;\n}\n\n/**\n * Self-managed source ids. Projects use their raw Linear project id (no prefix,\n * preserving existing intake bindings). Teams are prefixed so the two never\n * collide and callers can tell them apart.\n */\nconst SELF_MANAGED_TEAM_SOURCE_PREFIX = 'linear-team:';\n\nfunction encodeSelfManagedTeamSourceId(teamId: string): string {\n return `${SELF_MANAGED_TEAM_SOURCE_PREFIX}${teamId}`;\n}\n\nfunction isSelfManagedTeamSourceId(sourceId: string): boolean {\n return sourceId.startsWith(SELF_MANAGED_TEAM_SOURCE_PREFIX);\n}\n\nfunction decodeSelfManagedTeamSourceId(sourceId: string): string {\n return sourceId.slice(SELF_MANAGED_TEAM_SOURCE_PREFIX.length);\n}\n\n/**\n * Split selected source ids into raw project ids and raw team ids. A team\n * source id carries the `linear-team:` prefix; everything else is a project id.\n */\nfunction splitSelfManagedSourceIds(sourceIds: string[]): { projectIds: string[]; teamIds: string[] } {\n const projectIds: string[] = [];\n const teamIds: string[] = [];\n for (const sourceId of sourceIds) {\n if (isSelfManagedTeamSourceId(sourceId)) teamIds.push(decodeSelfManagedTeamSourceId(sourceId));\n else projectIds.push(sourceId);\n }\n return { projectIds, teamIds };\n}\n\ntype SelfManagedListCursor = {\n v: 1;\n sourceSet: string;\n projects: string | null;\n teams: string | null;\n};\n\nfunction linearSourceSetFingerprint(sourceIds: string[], attributionSourceIds: string[]): string {\n const scope = {\n sourceIds: [...new Set(sourceIds)].sort(),\n attributionSourceIds: [...new Set(attributionSourceIds)].sort(),\n };\n return createHash('sha256').update(JSON.stringify(scope)).digest('base64url');\n}\n\nfunction invalidLinearCursor(): Error {\n return Object.assign(new Error('Linear cursor is invalid or stale.'), { code: 'invalid_cursor' as const });\n}\n\nfunction isCursorValue(value: unknown): value is string | null {\n return value === null || typeof value === 'string';\n}\n\nfunction decodeSelfManagedListCursor(\n cursor: string | undefined,\n sourceIds: string[],\n attributionSourceIds: string[],\n): { projects: string | null | undefined; teams: string | null | undefined } {\n const { projectIds, teamIds } = splitSelfManagedSourceIds(sourceIds);\n if (!cursor) {\n return {\n projects: projectIds.length > 0 ? undefined : null,\n teams: teamIds.length > 0 ? undefined : null,\n };\n }\n try {\n const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as Partial<SelfManagedListCursor>;\n if (\n parsed.v !== 1 ||\n parsed.sourceSet !== linearSourceSetFingerprint(sourceIds, attributionSourceIds) ||\n !isCursorValue(parsed.projects) ||\n !isCursorValue(parsed.teams)\n ) {\n throw invalidLinearCursor();\n }\n return {\n projects: parsed.projects,\n teams: parsed.teams,\n };\n } catch {\n throw invalidLinearCursor();\n }\n}\n\nfunction encodeSelfManagedListCursor(\n state: Pick<SelfManagedListCursor, 'projects' | 'teams'>,\n sourceIds: string[],\n attributionSourceIds: string[],\n): string | null {\n if (state.projects === null && state.teams === null) return null;\n return Buffer.from(\n JSON.stringify({\n v: 1,\n sourceSet: linearSourceSetFingerprint(sourceIds, attributionSourceIds),\n ...state,\n } satisfies SelfManagedListCursor),\n ).toString('base64url');\n}\n\n/**\n * Deduplicate issues that surfaced from both a selected team and one of its\n * selected projects. Keeps one entry per Linear issue UUID.\n *\n * Tie-breaker — MOST-SPECIFIC-WINS: an issue in a selected project is\n * attributed to that project source (routes to the project's board); the team\n * source covers only the remainder (projectless issues and issues in projects\n * that were not separately selected). Change the comparison here to change the\n * routing policy — this is the single precedence point for the self-managed\n * integration, mirroring the platform-backed one.\n */\nfunction dedupeSelfManagedIssues(\n issues: Array<IntakeIssue & { sourceId?: string | null }>,\n): Array<IntakeIssue & { sourceId?: string | null }> {\n const isProjectSource = (sourceId: string | null | undefined): boolean =>\n typeof sourceId === 'string' && sourceId.length > 0 && !isSelfManagedTeamSourceId(sourceId);\n const winners = new Map<string, IntakeIssue & { sourceId?: string | null }>();\n for (const issue of issues) {\n const existing = winners.get(issue.id);\n if (!existing) {\n winners.set(issue.id, issue);\n continue;\n }\n // Project source beats team source; otherwise keep the first seen.\n if (isProjectSource(issue.sourceId) && !isProjectSource(existing.sourceId)) {\n winners.set(issue.id, issue);\n }\n }\n const seen = new Set<string>();\n const ordered: Array<IntakeIssue & { sourceId?: string | null }> = [];\n for (const issue of issues) {\n if (seen.has(issue.id)) continue;\n seen.add(issue.id);\n ordered.push(winners.get(issue.id)!);\n }\n return ordered;\n}\n\nfunction linearIssueToIntakeIssue(issue: Omit<LinearIssue, 'projectId'> & { projectId?: string | null }): IntakeIssue {\n return {\n id: issue.id,\n sourceId: issue.projectId ?? null,\n projectId: issue.projectId ?? null,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: issue.creator,\n state: issue.state,\n stateType: issue.stateType,\n priority: issue.priorityLabel,\n assignee: issue.assignee,\n source: issue.team,\n labels: issue.labels,\n commentCount: null,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AA6G7B,MAAM,0BAA0B;AAChC,MAAM,2BAA2B;AACjC,MAAM,yBAAyB;AAC/B,MAAM,yBAAyB;;AAE/B,MAAM,2BAA2B;;AAGjC,MAAM,wBAAwB;;AAG9B,MAAM,oBAAoB;AAE1B,MAAM,eAAe;;AAGrB,IAAa,4BAAb,cAA+C,MAAM;CACnD,cAAc;EACZ,MAAM,+EAA+E;CACvF;AACF;;AA2EA,eAAe,cAAiB,aAAqB,OAAe,WAAiD;CACnH,MAAM,MAAM,MAAM,MAAM,oBAAoB;EAC1C,QAAQ;EACR,QAAQ,YAAY,QAAQ,IAAM;EAClC,SAAS;GACP,gBAAgB;GAChB,eAAe,UAAU;EAC3B;EACA,MAAM,KAAK,UAAU;GAAE;GAAO;EAAU,CAAC;CAC3C,CAAC;CACD,IAAI,CAAC,IAAI,IAAI;EAGX,IAAI,SAAwB;EAC5B,IAAI;GAEF,UAAS,MADc,IAAI,KAAK,EAAA,CACf,SAAS,EAAE,EAAE,WAAW;EAC3C,QAAQ,CAER;EACA,MAAM,sBAAM,IAAI,MAAM,8BAA8B,IAAI,OAAO,GAAG,SAAS,KAAK,WAAW,IAAI;EAC/F,IAA6B,SAAS,IAAI;EAC1C,MAAM;CACR;CACA,MAAM,OAAQ,MAAM,IAAI,KAAK;CAC7B,IAAI,KAAK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AG;EACH,WAAW,2BAA2B,WAAW,oBAAoB;EACrE,GAAG;CACL,CAAiC,CACnC,CAAC,CAAC,SAAS,WAAW;AACxB;;;;;;;;;;;;AAaA,SAAS,wBACP,QACmD;CACnD,MAAM,mBAAmB,aACvB,OAAO,aAAa,YAAY,SAAS,SAAS,KAAK,CAAC,0BAA0B,QAAQ;CAC5F,MAAM,0BAAU,IAAI,IAAwD;CAC5E,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,QAAQ,IAAI,MAAM,EAAE;EACrC,IAAI,CAAC,UAAU;GACb,QAAQ,IAAI,MAAM,IAAI,KAAK;GAC3B;EACF;EAEA,IAAI,gBAAgB,MAAM,QAAQ,KAAK,CAAC,gBAAgB,SAAS,QAAQ,GACvE,QAAQ,IAAI,MAAM,IAAI,KAAK;CAE/B;CACA,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,UAA6D,CAAC;CACpE,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,KAAK,IAAI,MAAM,EAAE,GAAG;EACxB,KAAK,IAAI,MAAM,EAAE;EACjB,QAAQ,KAAK,QAAQ,IAAI,MAAM,EAAE,CAAE;CACrC;CACA,OAAO;AACT;AAEA,SAAS,yBAAyB,OAAoF;CACpH,OAAO;EACL,IAAI,MAAM;EACV,UAAU,MAAM,aAAa;EAC7B,WAAW,MAAM,aAAa;EAC9B,YAAY,MAAM;EAClB,OAAO,MAAM;EACb,KAAK,MAAM;EACX,QAAQ,MAAM;EACd,OAAO,MAAM;EACb,WAAW,MAAM;EACjB,UAAU,MAAM;EAChB,UAAU,MAAM;EAChB,QAAQ,MAAM;EACd,QAAQ,MAAM;EACd,cAAc;EACd,WAAW,MAAM;EACjB,WAAW,MAAM;CACnB;AACF"}
|
|
1
|
+
{"version":3,"file":"integration.js","names":["#storage","#projects","#auth","#updateTokens","#inflightRefreshes","#connectionChecks","#orgIdByResourceId","#resolveIntakeDispatch","#listIntakeIssues","#getIntakeIssue","#createIntakeComment","#updateIntakeIssue","#clientId","#clientSecret","#rules","#requestTokens","#listTeamWorkflowStates","#fetchRemainingIssueComments"],"sources":["../../../src/integrations/linear/integration.ts"],"sourcesContent":["/**\n * `LinearIntegration` — the self-contained Linear integration.\n *\n * Implements the system-wide `FactoryIntegration` contract\n * (`../factory-integration.ts`): the deploy entry reads the Linear OAuth env\n * vars ONCE, constructs an instance with explicit credentials, and passes it\n * to `MastraFactory`. Everything Linear-flavored the system does — the OAuth\n * connect/callback flow, workspace/project/issue reads for Intake, and the\n * agent's issue tools — flows through this instance. No other module reads\n * `LINEAR_*` env vars.\n *\n * The class owns:\n * - OAuth: the user-facing authorize URL, code exchange, and refresh-token\n * rotation against Linear's `/oauth/token` endpoint.\n * - GraphQL reads/writes: viewer workspace, projects, active issues for\n * Intake, full issue detail (description + discussion), issue comments.\n * - The HTTP surface (`routes()`) and per-request agent tools\n * (`agentTools()`), delegating to `./routes.ts` / `./agent-tools.ts` with\n * `this` as the API client.\n */\n\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\nimport type { IntegrationConnection } from '../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n ListIntakeIssuesInput,\n UpdateIntakeIssueInput,\n} from '../../capabilities/intake.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntegrationStorageHandle } from '../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { IssueReconcileWorker } from '../issue-reconcile-worker.js';\nimport { buildLinearAgentTools } from './agent-tools.js';\nimport type { LinearEventRules, LinearRuleOverrides } from './default-rules.js';\nimport { resolveLinearRules } from './default-rules.js';\nimport { attachLinearIssueReconciler } from './issue-reconciler.js';\nimport { linearIssueReconciliationEnabled, linearIssueReconciliationInterval } from './reconciliation-config.js';\nimport { buildLinearRoutes } from './routes.js';\nimport { attachLinearRules } from './rules.js';\nimport type { LinearConnectionRow, LinearStorageHandle, UpsertLinearConnectionInput } from './storage.js';\n\nconst LINEAR_GRAPHQL_URL = 'https://api.linear.app/graphql';\nconst LINEAR_TOKEN_URL = 'https://api.linear.app/oauth/token';\nconst LINEAR_AUTHORIZE_URL = 'https://linear.app/oauth/authorize';\n\n/** Credentials and optional event rules for the Linear OAuth application. */\nexport interface LinearIntegrationConfig {\n /** Per-event replacements; omitted events retain defaults, null disables. */\n rules?: LinearRuleOverrides;\n /** OAuth client id of the Linear application. */\n clientId: string;\n /** OAuth client secret of the Linear application. */\n clientSecret: string;\n}\n\n/**\n * Tokens minted by Linear's `/oauth/token` endpoint. Linear access tokens\n * expire (24h) and refresh tokens rotate: every refresh invalidates the old\n * pair, so callers must persist the whole set after each exchange.\n */\nexport interface LinearTokenSet {\n accessToken: string;\n /** Null when Linear issued no refresh token (legacy non-expiring apps). */\n refreshToken: string | null;\n /** Null when Linear reported no `expires_in`. */\n expiresAt: Date | null;\n /** Scopes granted to the token as reported by Linear; null when omitted. */\n scope: string | null;\n}\n\nexport interface LinearWorkspace {\n name: string;\n urlKey: string;\n}\n\nexport interface LinearIssue {\n id: string;\n projectId: string | null;\n /** Backend workspace identity when source ids span multiple workspaces. */\n workspaceId?: string;\n /** Raw Linear team id for exact team-source attribution. */\n teamId: string | null;\n /** Human key like `ENG-123`. */\n identifier: string;\n title: string;\n url: string;\n /** Workflow state name, e.g. `In Progress`. */\n state: string;\n /** Workflow state type, e.g. `backlog` / `unstarted` / `started` / `triage`. */\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the Linear user who created the issue, when Linear returns one. */\n creator: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface LinearIssuePage {\n issues: LinearIssue[];\n /** Opaque cursor for the next page, or `null` on the last page. */\n nextCursor: string | null;\n}\n\nexport interface LinearProjectTeam {\n id: string;\n /** Short team key, e.g. `ENG`. */\n key: string;\n name: string;\n}\n\nexport interface LinearProject {\n id: string;\n name: string;\n /** Project state, e.g. `planned` / `started` / `paused` / `completed`. */\n state: string;\n /** Teams the project belongs to (the Settings picker groups by these). */\n teams: LinearProjectTeam[];\n}\n\n/** A Linear team, selectable as an intake source in its own right. */\nexport interface LinearTeam {\n id: string;\n /** Short team key, e.g. `ENG`. */\n key: string;\n name: string;\n /** Opaque intake source identifier. Optional on the wire for compatibility. */\n sourceId?: string;\n}\n\nexport interface LinearIssueComment {\n author: string | null;\n body: string;\n createdAt: string;\n}\n\n/** Full issue payload for agent context: everything in {@link LinearIssue} plus description and discussion. */\nexport interface LinearIssueDetail extends LinearIssue {\n /** Markdown body of the issue, or `null` when empty. */\n description: string | null;\n /** Discussion comments, oldest first. */\n comments: LinearIssueComment[];\n}\n\n/** The comment created by {@link LinearIntegration.createIssueComment}. */\nexport interface LinearCreatedComment {\n id: string;\n url: string;\n}\n\nconst LINEAR_ISSUES_PAGE_SIZE = 30;\nconst ISSUE_COMMENTS_PAGE_SIZE = 50;\nconst LINEAR_TEAMS_PAGE_SIZE = 100;\nconst LINEAR_TEAMS_MAX_PAGES = 20;\n/** Hard stop for comment pagination so a misbehaving cursor can't loop forever. */\nconst ISSUE_COMMENTS_MAX_PAGES = 20;\n\n/** Refresh this many ms before the recorded expiry to absorb clock skew. */\nconst TOKEN_REFRESH_SKEW_MS = 60_000;\n\n/** Re-check an org's Linear connection (and its scopes) at most this often. */\nconst CONNECTION_TTL_MS = 60_000;\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Thrown when the org's Linear authorization can no longer be renewed. */\nexport class LinearReauthRequiredError extends Error {\n constructor() {\n super('Linear authorization expired. Reconnect Linear to keep syncing intake issues.');\n }\n}\n\n/** Cached result of {@link LinearIntegration.checkConnection}. */\nexport interface LinearConnectionCheck {\n connected: boolean;\n /** Whether the granted OAuth scope allows posting issue comments. */\n canComment: boolean;\n checkedAt: number;\n}\n\ninterface IssuesQueryData {\n issues: {\n nodes: Array<{\n id: string;\n identifier: string;\n title: string;\n url: string;\n priorityLabel: string;\n createdAt: string;\n updatedAt: string;\n state: { name: string; type: string };\n project: { id: string } | null;\n assignee: { name: string } | null;\n creator: { name: string } | null;\n team: { id: string; key: string } | null;\n labels: { nodes: Array<{ name: string }> };\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n}\n\ninterface IssueCommentNode {\n body: string;\n createdAt: string;\n user: { name: string } | null;\n}\n\ninterface IssueCommentsPage {\n nodes: IssueCommentNode[];\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n}\n\ninterface IssueDetailQueryData {\n issue: {\n id: string;\n identifier: string;\n title: string;\n description: string | null;\n url: string;\n priorityLabel: string;\n createdAt: string;\n updatedAt: string;\n state: { name: string; type: string };\n project: { id: string } | null;\n assignee: { name: string } | null;\n creator: { name: string } | null;\n team: { id: string; key: string } | null;\n labels: { nodes: Array<{ name: string }> };\n comments: IssueCommentsPage;\n } | null;\n}\n\ninterface IssueCommentsQueryData {\n issue: { comments: IssueCommentsPage } | null;\n}\n\ninterface IssueIdQueryData {\n issue: { id: string } | null;\n}\n\ninterface CommentCreateMutationData {\n commentCreate: { success: boolean; comment: { id: string; url: string } | null };\n}\n\n/** POST a GraphQL query to Linear with the given OAuth access token. */\nasync function linearGraphql<T>(accessToken: string, query: string, variables?: Record<string, unknown>): Promise<T> {\n const res = await fetch(LINEAR_GRAPHQL_URL, {\n method: 'POST',\n signal: AbortSignal.timeout(15_000),\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({ query, variables }),\n });\n if (!res.ok) {\n // Linear returns GraphQL errors (validation, missing scopes, …) with a\n // 400 status — surface the actual message instead of just the code.\n let detail: string | null = null;\n try {\n const errBody = (await res.json()) as { errors?: Array<{ message?: string }> };\n detail = errBody.errors?.[0]?.message ?? null;\n } catch {\n // Non-JSON error body; fall back to the status code alone.\n }\n const err = new Error(`Linear API request failed (${res.status})${detail ? `: ${detail}` : ''}`);\n (err as { status?: number }).status = res.status;\n throw err;\n }\n const body = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };\n if (body.errors?.length) {\n throw new Error(`Linear API error: ${body.errors[0]?.message ?? 'unknown error'}`);\n }\n if (!body.data) {\n throw new Error('Linear API returned no data.');\n }\n return body.data;\n}\n\nexport class LinearIntegration implements FactoryIntegration {\n /** Stable integration identifier (see `../base.ts`). */\n readonly id = 'linear';\n /** Bound once by the factory via `initialize()` before any surface is used. */\n #storage: LinearStorageHandle | undefined;\n #projects: FactoryProjectsStorage | undefined;\n #auth: RouteAuth | undefined;\n\n /** Bind Linear's slice of the generic integration storage, the projects domain, and the host auth seam. */\n initialize({\n storage,\n projects,\n auth,\n }: {\n storage: IntegrationStorageHandle;\n projects: FactoryProjectsStorage;\n auth: RouteAuth;\n }): void {\n this.#storage = storage as unknown as LinearStorageHandle;\n this.#projects = projects;\n this.#auth = auth;\n }\n\n get storage(): LinearStorageHandle {\n if (!this.#storage) {\n throw new Error('LinearIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#storage;\n }\n\n /** Factory projects domain — maps a session's resourceId to its owning org. */\n get projects(): FactoryProjectsStorage {\n if (!this.#projects) {\n throw new Error('LinearIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#projects;\n }\n\n /**\n * Whether the host runs with web auth enabled. Linear connections are\n * org-owned, so every Linear surface is inert without a tenant auth seam.\n */\n get authEnabled(): boolean {\n return this.#auth?.enabled() ?? false;\n }\n\n // ── Connection + OAuth token lifecycle ───────────────────────────────────\n\n /** Load the org's Linear connection, or `null` when not connected. */\n async loadConnection(orgId: string): Promise<LinearConnectionRow | null> {\n const connection = await this.storage.connections.get(orgId);\n if (!connection) return null;\n const { data } = connection;\n return {\n id: connection.id,\n orgId: connection.orgId,\n userId: connection.userId,\n accessToken: data.accessToken,\n scope: data.scope ?? null,\n refreshToken: data.refreshToken ?? null,\n expiresAt: data.expiresAtMs === null || data.expiresAtMs === undefined ? null : new Date(data.expiresAtMs),\n workspaceName: data.workspaceName ?? null,\n workspaceUrlKey: data.workspaceUrlKey ?? null,\n createdAt: connection.createdAt,\n updatedAt: connection.updatedAt,\n };\n }\n\n /** Insert or replace the org's connection (one per org). */\n async upsertConnection(input: UpsertLinearConnectionInput): Promise<void> {\n await this.storage.connections.upsert(input.orgId, {\n userId: input.userId,\n data: {\n accessToken: input.accessToken,\n refreshToken: input.refreshToken,\n expiresAtMs: input.expiresAt?.getTime() ?? null,\n scope: input.scope,\n workspaceName: input.workspaceName,\n workspaceUrlKey: input.workspaceUrlKey,\n },\n });\n // Let the agent tools see the new connection immediately.\n this.invalidateConnectionCache(input.orgId);\n }\n\n /** Persist a rotated token set on the org's existing connection row. */\n async #updateTokens(orgId: string, tokens: LinearTokenSet): Promise<void> {\n await this.storage.connections.update(orgId, data => ({\n ...data,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAtMs: tokens.expiresAt?.getTime() ?? null,\n // Refresh responses may omit scope; keep the recorded grant.\n scope: tokens.scope ?? data.scope,\n }));\n }\n\n /**\n * Whether the connection's token can post issue comments. Legacy rows\n * without a recorded scope were minted with `read` only, so they count as\n * read-only until the org reconnects Linear.\n */\n canPostComments(connection: LinearConnectionRow): boolean {\n const scopes = (connection.scope ?? '').split(/[\\s,]+/).filter(Boolean);\n return scopes.some(scope => scope === 'comments:create' || scope === 'write' || scope === 'admin');\n }\n\n /**\n * In-flight refreshes keyed by org. Linear rotates refresh tokens, so two\n * concurrent refreshes with the same token would invalidate each other —\n * single-flight ensures one exchange per org and shares the result.\n */\n readonly #inflightRefreshes = new Map<string, Promise<string>>();\n\n /**\n * Return a usable access token for the connection, proactively refreshing\n * it when the recorded expiry is past (or imminent). Throws\n * `LinearReauthRequiredError` when the token is expired and cannot be\n * refreshed — the org has to go through the OAuth flow again.\n */\n async getFreshAccessToken(connection: LinearConnectionRow): Promise<string> {\n const expired =\n connection.expiresAt !== null && connection.expiresAt.getTime() - TOKEN_REFRESH_SKEW_MS <= Date.now();\n if (!expired) return connection.accessToken;\n\n if (!connection.refreshToken) {\n // Legacy row from before refresh-token support: nothing to renew with.\n throw new LinearReauthRequiredError();\n }\n\n const existing = this.#inflightRefreshes.get(connection.orgId);\n if (existing) return existing;\n\n // The caller may hold a stale row: another request could have refreshed\n // and rotated the refresh token since this row was loaded. Reload before\n // refreshing so we don't burn the rotated token and force a false reauth.\n const latest = await this.loadConnection(connection.orgId);\n if (!latest) throw new LinearReauthRequiredError();\n\n const concurrent = this.#inflightRefreshes.get(connection.orgId);\n if (concurrent) return concurrent;\n\n const latestExpired = latest.expiresAt !== null && latest.expiresAt.getTime() - TOKEN_REFRESH_SKEW_MS <= Date.now();\n if (!latestExpired) return latest.accessToken;\n if (!latest.refreshToken) throw new LinearReauthRequiredError();\n\n const refreshToken = latest.refreshToken;\n const refresh = (async () => {\n try {\n const tokens = await this.refreshAccessToken(refreshToken);\n await this.#updateTokens(connection.orgId, tokens);\n return tokens.accessToken;\n } catch (err) {\n const status = (err as { status?: number }).status;\n // invalid_grant surfaces as 400/401: the refresh token was revoked or\n // already rotated away. Terminal for this connection.\n if (status === 400 || status === 401) throw new LinearReauthRequiredError();\n throw err;\n } finally {\n this.#inflightRefreshes.delete(connection.orgId);\n }\n })();\n this.#inflightRefreshes.set(connection.orgId, refresh);\n return refresh;\n }\n\n // ── Connection checks for agent tools ────────────────────────────────────\n\n /** Re-check an org's Linear connection (and its scopes) at most this often. */\n readonly #connectionChecks = new Map<string, LinearConnectionCheck>();\n\n /**\n * Whether the org has an active connection and whether its granted scope\n * allows posting comments. Cached per org with a short TTL — tool-set\n * resolution runs on every request.\n */\n async checkConnection(orgId: string): Promise<LinearConnectionCheck> {\n const cached = this.#connectionChecks.get(orgId);\n if (cached && Date.now() - cached.checkedAt < CONNECTION_TTL_MS) return cached;\n const connection = await this.loadConnection(orgId);\n const check: LinearConnectionCheck = {\n connected: connection !== null,\n canComment: connection !== null && this.canPostComments(connection),\n checkedAt: Date.now(),\n };\n this.#connectionChecks.set(orgId, check);\n return check;\n }\n\n /**\n * Drop the cached connection check for an org. Called after a connection is\n * persisted so the tools show up on the very next run instead of after the\n * TTL lapses.\n */\n invalidateConnectionCache(orgId: string): void {\n this.#connectionChecks.delete(orgId);\n }\n\n /**\n * A project's org never changes, so the resourceId → orgId mapping is\n * cached forever. `null` marks resource ids that aren't factory projects\n * (e.g. local default resources) so we don't re-query them on every\n * tool-set resolution.\n */\n readonly #orgIdByResourceId = new Map<string, string | null>();\n\n /** Map a session's resourceId to its owning org, or `null` when it isn't a project. */\n async resolveOrgId(resourceId: string): Promise<string | null> {\n const cached = this.#orgIdByResourceId.get(resourceId);\n if (cached !== undefined) return cached;\n // Non-UUID resource ids (local/dev resources) would make the uuid column\n // comparison throw — they're definitively \"not a project\", so cache that.\n if (!UUID_PATTERN.test(resourceId)) {\n this.#orgIdByResourceId.set(resourceId, null);\n return null;\n }\n let orgId: string | null;\n try {\n await this.projects.ensureReady();\n const project = await this.projects.getById({ id: resourceId });\n orgId = project?.orgId ?? null;\n } catch {\n // Transient database failure: skip the tools for this request but don't\n // cache the miss, so the next request retries the lookup.\n return null;\n }\n this.#orgIdByResourceId.set(resourceId, orgId);\n return orgId;\n }\n\n /** Test hook: clear the org/connection caches between specs. */\n clearCaches(): void {\n this.#orgIdByResourceId.clear();\n this.#connectionChecks.clear();\n }\n\n readonly intake: Intake = {\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: async ({ orgId }) => {\n const connection = await this.loadConnection(orgId);\n if (!connection) return [];\n const accessToken = await this.getFreshAccessToken(connection);\n const [projects, teams] = await Promise.all([this.listProjects(accessToken), this.listTeams(accessToken)]);\n return [\n ...projects.map(project => ({\n id: project.id,\n name: project.name,\n type: 'project' as const,\n })),\n ...teams.map(team => ({\n id: encodeSelfManagedTeamSourceId(team.id),\n name: team.name,\n type: 'team' as const,\n metadata: { teamKey: team.key },\n })),\n ];\n },\n listItems: async ({ orgId, sourceIds, attributionSourceIds, cursor }) => {\n if (sourceIds.length === 0) return { items: [], nextCursor: null };\n const connection = await this.loadConnection(orgId);\n if (!connection) return { items: [], nextCursor: null };\n const accessToken = await this.getFreshAccessToken(connection);\n const page = await this.#listIntakeIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds,\n attributionSourceIds,\n cursor,\n });\n return {\n items: page.issues.flatMap(issue => {\n if (!issue.sourceId) return [];\n return [\n {\n source: { type: 'issue', externalId: issue.id, url: issue.url },\n sourceId: issue.sourceId,\n title: `${issue.identifier}: ${issue.title}`,\n status: issue.state ?? '',\n labels: issue.labels,\n assignee: issue.assignee,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n metadata: {\n identifier: issue.identifier,\n ...(issue.projectId ? { linearProjectId: issue.projectId } : {}),\n stateType: issue.stateType,\n priority: issue.priority,\n team: issue.source,\n },\n },\n ];\n }),\n nextCursor: page.nextCursor,\n };\n },\n listIssues: input => this.#listIntakeIssues(input),\n getIssue: input => this.#getIntakeIssue(input),\n createComment: input => this.#createIntakeComment(input),\n updateIssue: input => this.#updateIntakeIssue(input),\n };\n\n /**\n * Background-dispatch context: the org's OAuth connection with a fresh\n * token. Linear work items store the issue UUID directly as `externalId`.\n */\n async #resolveIntakeDispatch({\n orgId,\n externalSource,\n }: {\n orgId: string;\n externalSource: { type: string; externalId: string };\n }): Promise<{ connection: IntegrationConnection; issueId: string } | null> {\n if (externalSource.type !== 'issue') return null;\n const connection = await this.loadConnection(orgId);\n if (!connection) return null;\n const accessToken = await this.getFreshAccessToken(connection);\n return { connection: { type: 'oauth', accessToken }, issueId: externalSource.externalId };\n }\n /**\n * The OAuth connect/callback flow round-trips a signed `state` through\n * Linear, so a multi-replica deploy needs a deployment-stable state secret.\n */\n readonly requiresStableStateSigner = true;\n\n readonly #clientId: string;\n readonly #clientSecret: string;\n\n readonly #rules: LinearEventRules;\n\n get rules(): LinearEventRules {\n return this.#rules;\n }\n\n constructor(config: LinearIntegrationConfig) {\n this.#rules = resolveLinearRules(config.rules);\n const missing = (['clientId', 'clientSecret'] as const).filter(key => !config[key]);\n if (missing.length > 0) {\n throw new Error(`LinearIntegration is missing required config: ${missing.join(', ')}.`);\n }\n this.#clientId = config.clientId;\n this.#clientSecret = config.clientSecret;\n }\n\n // ── OAuth ────────────────────────────────────────────────────────────────\n\n /**\n * Build the OAuth authorize URL. `prompt=consent` forces the workspace\n * picker even for an already-authorized user, so \"reconnect\" can switch\n * workspaces.\n */\n buildAuthorizeUrl(state: string, redirectUri: string): string {\n const url = new URL(LINEAR_AUTHORIZE_URL);\n url.searchParams.set('client_id', this.#clientId);\n url.searchParams.set('redirect_uri', redirectUri);\n url.searchParams.set('response_type', 'code');\n // `comments:create` lets the agent's linear_create_comment tool post\n // comments; everything else the integration does is read-only.\n url.searchParams.set('scope', 'read,comments:create');\n url.searchParams.set('state', state);\n url.searchParams.set('prompt', 'consent');\n return url.toString();\n }\n\n /** Exchange an OAuth `code` for a workspace-scoped token set. */\n async exchangeOAuthCode(code: string, redirectUri: string): Promise<LinearTokenSet> {\n return this.#requestTokens({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }, 'token exchange');\n }\n\n /**\n * Exchange a refresh token for a new token set. Linear rotates refresh\n * tokens, so the returned set replaces the stored one entirely. A 400/401\n * here means the refresh token is invalid/revoked and the org must\n * re-authorize.\n */\n async refreshAccessToken(refreshToken: string): Promise<LinearTokenSet> {\n return this.#requestTokens({ grant_type: 'refresh_token', refresh_token: refreshToken }, 'token refresh');\n }\n\n /** POST to Linear's token endpoint and normalize the response. */\n async #requestTokens(params: Record<string, string>, label: string): Promise<LinearTokenSet> {\n const res = await fetch(LINEAR_TOKEN_URL, {\n method: 'POST',\n signal: AbortSignal.timeout(10_000),\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n ...params,\n client_id: this.#clientId,\n client_secret: this.#clientSecret,\n }),\n });\n if (!res.ok) {\n const err = new Error(`Linear ${label} failed (${res.status})`);\n (err as { status?: number }).status = res.status;\n throw err;\n }\n const body = (await res.json()) as {\n access_token?: string;\n refresh_token?: string;\n expires_in?: number;\n scope?: string;\n };\n if (!body.access_token) {\n throw new Error(`Linear ${label} returned no access token.`);\n }\n return {\n accessToken: body.access_token,\n refreshToken: body.refresh_token ?? null,\n expiresAt: typeof body.expires_in === 'number' ? new Date(Date.now() + body.expires_in * 1000) : null,\n scope: body.scope ?? null,\n };\n }\n\n // ── GraphQL reads/writes ─────────────────────────────────────────────────\n\n /** Fetch the workspace (organization) the access token is scoped to. */\n async fetchWorkspace(accessToken: string): Promise<LinearWorkspace> {\n const data = await linearGraphql<{ organization: { name: string; urlKey: string } }>(\n accessToken,\n `query { organization { name urlKey } }`,\n );\n return { name: data.organization.name, urlKey: data.organization.urlKey };\n }\n\n async #listIntakeIssues(input: ListIntakeIssuesInput): Promise<{ issues: IntakeIssue[]; nextCursor: string | null }> {\n const accessToken = getLinearAccessToken(input.connection);\n if (input.sourceIds.length === 0) return { issues: [], nextCursor: null };\n const attributionSourceIds = input.attributionSourceIds ?? input.sourceIds;\n const { projectIds, teamIds } = splitSelfManagedSourceIds(input.sourceIds);\n const cursors = await decodeSelfManagedListCursor(input.cursor, input.sourceIds, attributionSourceIds);\n\n // Project-only intake still uses one Linear query, but its provider cursor\n // is wrapped so a later source-selection change cannot reinterpret it.\n if (teamIds.length === 0) {\n if (cursors.projects === null) return { issues: [], nextCursor: null };\n const result = await this.listActiveIssues(accessToken, cursors.projects, projectIds, input.labels);\n return {\n issues: result.issues.map(issue => linearIssueToIntakeIssue(issue)),\n nextCursor: await encodeSelfManagedListCursor(\n { projects: result.nextCursor, teams: null },\n input.sourceIds,\n attributionSourceIds,\n ),\n };\n }\n\n // A team is selected. List projects and teams separately (the two Linear\n // filters would AND together in one query) and stamp each issue with the\n // selected source that surfaced it. Each source kind paginates on its own\n // cursor, carried in a compound cursor when both are present.\n const projectResult =\n projectIds.length > 0 && cursors.projects !== null\n ? await this.listActiveIssues(accessToken, cursors.projects, projectIds, input.labels)\n : { issues: [], nextCursor: null };\n const teamResult =\n cursors.teams !== null\n ? await this.listActiveIssues(accessToken, cursors.teams, undefined, input.labels, teamIds)\n : { issues: [], nextCursor: null };\n\n // Stamp project issues with their (selected) project id; stamp team issues\n // with the team source id. A team issue whose project was also selected is\n // reconciled by the dedupe step below (project wins).\n const projectIssues = projectResult.issues.map(issue => linearIssueToIntakeIssue(issue));\n const selectedTeamSourceById = new Map(teamIds.map(teamId => [teamId, encodeSelfManagedTeamSourceId(teamId)]));\n const selectedProjectIds = new Set(splitSelfManagedSourceIds(attributionSourceIds).projectIds);\n const teamIssues = teamResult.issues\n .filter(issue => issue.projectId === null || !selectedProjectIds.has(issue.projectId))\n .map(issue => {\n const teamSourceId = issue.teamId ? selectedTeamSourceById.get(issue.teamId) : undefined;\n if (!teamSourceId) throw new Error('Linear returned an issue outside the selected teams.');\n return { ...linearIssueToIntakeIssue(issue), sourceId: teamSourceId };\n });\n\n const deduped = dedupeSelfManagedIssues([...projectIssues, ...teamIssues]);\n return {\n issues: deduped,\n nextCursor: await encodeSelfManagedListCursor(\n { projects: projectResult.nextCursor, teams: teamResult.nextCursor },\n input.sourceIds,\n attributionSourceIds,\n ),\n };\n }\n\n async #getIntakeIssue(input: GetIntakeIssueInput): Promise<IntakeIssueDetail | null> {\n const accessToken = getLinearAccessToken(input.connection);\n const issue = await this.fetchIssueDetail(accessToken, input.issueId);\n if (!issue) return null;\n return {\n ...linearIssueToIntakeIssue(issue),\n description: issue.description,\n commentCount: issue.comments.length,\n comments: issue.comments,\n };\n }\n\n async #createIntakeComment(input: CreateIntakeCommentInput): Promise<{ id: string; url: string } | null> {\n const accessToken = getLinearAccessToken(input.connection);\n return this.createIssueComment(accessToken, input.issueId, input.body);\n }\n\n async #updateIntakeIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> {\n const accessToken = getLinearAccessToken(input.connection);\n const issue = await this.fetchIssueDetail(accessToken, input.issueId);\n if (!issue) return null;\n const teamKey = issue.team;\n if (!teamKey) return null;\n const states = await this.#listTeamWorkflowStates(accessToken, teamKey);\n let targetState: { id: string; name: string; type: string } | null = null;\n if (input.state.kind === 'byType') {\n const wantedType = input.state.stateType;\n targetState = states.find(state => state.type === wantedType) ?? null;\n } else {\n const wanted = input.state.name.toLowerCase();\n targetState = states.find(state => state.name.toLowerCase() === wanted) ?? null;\n }\n if (!targetState) return null;\n if (targetState.name === issue.state) {\n return linearIssueToIntakeIssue(issue);\n }\n const data = await linearGraphql<{ issueUpdate: { success: boolean } }>(\n accessToken,\n `mutation UpdateIssueState($id: String!, $stateId: String!) {\n issueUpdate(id: $id, input: { stateId: $stateId }) { success }\n }`,\n { id: issue.id, stateId: targetState.id },\n );\n if (!data.issueUpdate.success) {\n throw new Error('Linear did not accept the issue update.');\n }\n const fresh = await this.fetchIssueDetail(accessToken, issue.id);\n if (!fresh) return null;\n return linearIssueToIntakeIssue(fresh);\n }\n\n async #listTeamWorkflowStates(\n accessToken: string,\n teamKey: string,\n ): Promise<Array<{ id: string; name: string; type: string }>> {\n const data = await linearGraphql<{\n team: { states: { nodes: Array<{ id: string; name: string; type: string }> } } | null;\n }>(\n accessToken,\n `query TeamStates($key: String!) {\n team(id: $key) { states(first: 100) { nodes { id name type } } }\n }`,\n { key: teamKey },\n );\n return data.team?.states.nodes ?? [];\n }\n\n /** List the workspace's projects (for the Settings intake-source picker). */\n async listProjects(accessToken: string): Promise<LinearProject[]> {\n const data = await linearGraphql<{\n projects: {\n nodes: Array<{\n id: string;\n name: string;\n state: string;\n teams: { nodes: Array<{ id: string; key: string; name: string }> };\n }>;\n };\n }>(\n accessToken,\n `query { projects(first: 100) { nodes { id name state teams(first: 10) { nodes { id key name } } } } }`,\n );\n return data.projects.nodes.map(node => ({\n id: node.id,\n name: node.name,\n state: node.state,\n teams: node.teams.nodes.map(team => ({ id: team.id, key: team.key, name: team.name })),\n }));\n }\n\n /** List the workspace's teams (for the Settings intake-source picker). */\n async listTeams(accessToken: string): Promise<LinearTeam[]> {\n const teams: Array<{ id: string; key: string; name: string }> = [];\n let after: string | undefined;\n for (let page = 0; page < LINEAR_TEAMS_MAX_PAGES; page += 1) {\n const data = await linearGraphql<{\n teams: {\n nodes: Array<{ id: string; key: string; name: string }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n }>(\n accessToken,\n `query Teams($first: Int!, $after: String) {\n teams(first: $first, after: $after) {\n nodes { id key name }\n pageInfo { hasNextPage endCursor }\n }\n }`,\n { first: LINEAR_TEAMS_PAGE_SIZE, ...(after ? { after } : {}) },\n );\n teams.push(...data.teams.nodes);\n if (!data.teams.pageInfo.hasNextPage || !data.teams.pageInfo.endCursor) break;\n // A page that hands back the cursor it was asked for would replay forever.\n if (data.teams.pageInfo.endCursor === after) throw invalidLinearCursor();\n after = data.teams.pageInfo.endCursor;\n }\n return teams.map(team => ({\n id: team.id,\n key: team.key,\n name: team.name,\n sourceId: encodeSelfManagedTeamSourceId(team.id),\n }));\n }\n\n sourceMatchesIssue(sourceId: string, issue: Pick<LinearIssueDetail, 'projectId' | 'teamId'>): boolean {\n return isSelfManagedTeamSourceId(sourceId)\n ? issue.teamId === decodeSelfManagedTeamSourceId(sourceId)\n : issue.projectId === sourceId;\n }\n\n /**\n * List one page of the workspace's active issues (triage/backlog/unstarted/\n * started — completed and canceled are excluded), most recently updated\n * first. When `projectIds` is provided, only issues from those projects are\n * returned. When `teamIds` is provided, only issues in those teams are\n * returned, including issues that belong to no project. Callers list team\n * sources and project sources in separate calls so the two filters are not\n * AND-ed together.\n */\n async listActiveIssues(\n accessToken: string,\n after?: string,\n projectIds?: string[],\n labels?: string[],\n teamIds?: string[],\n ): Promise<LinearIssuePage> {\n const normalizedLabels = [...new Set((labels ?? []).map(label => label.trim()).filter(Boolean))];\n const projectFilter = projectIds?.length ? ', project: { id: { in: $projectIds } }' : '';\n const projectVar = projectIds?.length ? ', $projectIds: [ID!]' : '';\n const teamFilter = teamIds?.length ? ', team: { id: { in: $teamIds } }' : '';\n const teamVar = teamIds?.length ? ', $teamIds: [ID!]' : '';\n const labelFilter = normalizedLabels.length > 0 ? ', labels: { name: { in: $labels } }' : '';\n const labelVar = normalizedLabels.length > 0 ? ', $labels: [String!]' : '';\n const data = await linearGraphql<IssuesQueryData>(\n accessToken,\n `query Intake($first: Int!, $after: String${projectVar}${teamVar}${labelVar}) {\n issues(\n first: $first\n after: $after\n orderBy: updatedAt\n filter: { state: { type: { in: [\"triage\", \"backlog\", \"unstarted\", \"started\"] } }${projectFilter}${teamFilter}${labelFilter} }\n ) {\n nodes {\n id\n identifier\n title\n url\n priorityLabel\n createdAt\n updatedAt\n state { name type }\n project { id }\n assignee { name }\n creator { name }\n team { id key }\n labels { nodes { name } }\n }\n pageInfo { hasNextPage endCursor }\n }\n }`,\n {\n first: LINEAR_ISSUES_PAGE_SIZE,\n after: after ?? null,\n ...(projectIds?.length ? { projectIds } : {}),\n ...(teamIds?.length ? { teamIds } : {}),\n ...(normalizedLabels.length > 0 ? { labels: normalizedLabels } : {}),\n },\n );\n const { nodes, pageInfo } = data.issues;\n return {\n issues: nodes.map(node => ({\n id: node.id,\n projectId: node.project?.id ?? null,\n identifier: node.identifier,\n title: node.title,\n url: node.url,\n state: node.state.name,\n stateType: node.state.type,\n priorityLabel: node.priorityLabel,\n assignee: node.assignee?.name ?? null,\n creator: node.creator?.name ?? null,\n team: node.team?.key ?? null,\n labels: node.labels.nodes.map(label => label.name),\n createdAt: node.createdAt,\n updatedAt: node.updatedAt,\n teamId: node.team?.id ?? null,\n })),\n nextCursor: pageInfo.hasNextPage ? pageInfo.endCursor : null,\n };\n }\n\n /** Follow `comments.pageInfo` until exhausted so long discussions aren't truncated. */\n async #fetchRemainingIssueComments(\n accessToken: string,\n issueId: string,\n firstPage: IssueCommentsPage,\n ): Promise<IssueCommentNode[]> {\n const nodes = [...firstPage.nodes];\n let { hasNextPage, endCursor } = firstPage.pageInfo;\n for (let page = 1; hasNextPage && endCursor && page < ISSUE_COMMENTS_MAX_PAGES; page++) {\n const data = await linearGraphql<IssueCommentsQueryData>(\n accessToken,\n `query IssueComments($id: String!, $first: Int!, $after: String!) {\n issue(id: $id) {\n comments(first: $first, after: $after) {\n nodes { body createdAt user { name } }\n pageInfo { hasNextPage endCursor }\n }\n }\n }`,\n { id: issueId, first: ISSUE_COMMENTS_PAGE_SIZE, after: endCursor },\n );\n const comments = data.issue?.comments;\n if (!comments) break;\n nodes.push(...comments.nodes);\n if (comments.pageInfo.hasNextPage && comments.pageInfo.endCursor === endCursor) throw invalidLinearCursor();\n ({ hasNextPage, endCursor } = comments.pageInfo);\n }\n return nodes;\n }\n\n /**\n * Fetch one issue with its description and comments. `idOrIdentifier`\n * accepts both the Linear UUID and the human key (`ENG-123`). Returns\n * `null` when the issue doesn't exist (Linear reports it as an \"Entity not\n * found\" error).\n */\n async fetchIssueDetail(\n accessToken: string,\n idOrIdentifier: string,\n _sourceIds?: string[],\n _routedSourceIds?: string[],\n ): Promise<LinearIssueDetail | null> {\n let data: IssueDetailQueryData;\n try {\n data = await linearGraphql<IssueDetailQueryData>(\n accessToken,\n `query IssueDetail($id: String!, $commentsFirst: Int!) {\n issue(id: $id) {\n id\n identifier\n title\n description\n url\n priorityLabel\n createdAt\n updatedAt\n state { name type }\n project { id }\n assignee { name }\n creator { name }\n team { id key }\n labels { nodes { name } }\n comments(first: $commentsFirst) {\n nodes { body createdAt user { name } }\n pageInfo { hasNextPage endCursor }\n }\n }\n }`,\n { id: idOrIdentifier, commentsFirst: ISSUE_COMMENTS_PAGE_SIZE },\n );\n } catch (err) {\n // Linear surfaces unknown ids/identifiers as a GraphQL \"Entity not\n // found\" error rather than a null node — map that to \"issue doesn't\n // exist\".\n if (err instanceof Error && /entity not found/i.test(err.message)) return null;\n throw err;\n }\n const issue = data.issue;\n if (!issue) return null;\n const allComments = await this.#fetchRemainingIssueComments(accessToken, issue.id, issue.comments);\n const comments = allComments.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());\n return {\n id: issue.id,\n projectId: issue.project?.id ?? null,\n teamId: issue.team?.id ?? null,\n identifier: issue.identifier,\n title: issue.title,\n description: issue.description?.trim() ? issue.description : null,\n url: issue.url,\n state: issue.state.name,\n stateType: issue.state.type,\n priorityLabel: issue.priorityLabel,\n assignee: issue.assignee?.name ?? null,\n creator: issue.creator?.name ?? null,\n team: issue.team?.key ?? null,\n labels: issue.labels.nodes.map(label => label.name),\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n comments: comments.map(comment => ({\n author: comment.user?.name ?? null,\n body: comment.body,\n createdAt: comment.createdAt,\n })),\n };\n }\n\n /**\n * Post a comment on an issue. `idOrIdentifier` accepts both the Linear UUID\n * and the human key (`ENG-123`) — the identifier is resolved to a UUID\n * first because `commentCreate` only accepts UUIDs. Returns `null` when the\n * issue doesn't exist.\n */\n async createIssueComment(\n accessToken: string,\n idOrIdentifier: string,\n body: string,\n ): Promise<LinearCreatedComment | null> {\n let issueId: string;\n try {\n const data = await linearGraphql<IssueIdQueryData>(\n accessToken,\n `query IssueId($id: String!) { issue(id: $id) { id } }`,\n { id: idOrIdentifier },\n );\n if (!data.issue) return null;\n issueId = data.issue.id;\n } catch (err) {\n if (err instanceof Error && /entity not found/i.test(err.message)) return null;\n throw err;\n }\n const data = await linearGraphql<CommentCreateMutationData>(\n accessToken,\n `mutation CommentCreate($input: CommentCreateInput!) {\n commentCreate(input: $input) { success comment { id url } }\n }`,\n { input: { issueId, body } },\n );\n if (!data.commentCreate.success || !data.commentCreate.comment) {\n throw new Error('Linear did not accept the comment.');\n }\n return data.commentCreate.comment;\n }\n\n // ── FactoryIntegration surface ───────────────────────────────────────────\n\n workers(ctx: IntegrationContext): MastraWorker[] {\n if (!linearIssueReconciliationEnabled()) return [];\n const reconcile = attachLinearIssueReconciler(this, ctx);\n if (!reconcile) return [];\n const intervalMs = linearIssueReconciliationInterval();\n return [\n new IssueReconcileWorker({\n integrationId: this.id,\n reconcile,\n ...(intervalMs ? { intervalMs } : {}),\n }),\n ];\n }\n\n /**\n * The integration's HTTP surface: `/web/linear/*` + `/auth/linear/*` Mastra\n * `apiRoutes` (status, OAuth connect/callback, projects + issues for\n * Intake). Handlers operate on this instance.\n */\n routes(ctx: IntegrationContext): ApiRoute[] {\n return buildLinearRoutes({\n linear: this,\n auth: ctx.auth,\n stateSigner: ctx.stateSigner,\n baseUrl: ctx.baseUrl,\n intake: ctx.storage.intake,\n projects: ctx.storage.projects,\n ingestFactoryIssues: attachLinearRules(this, ctx),\n workItems: ctx.runtime?.workItems,\n boards: ctx.runtime?.boards,\n });\n }\n\n /**\n * Org-scoped agent tools: issue detail + comment tools for sessions whose\n * project belongs to an org with an active Linear connection.\n */\n async agentTools(args: { requestContext: RequestContext }): Promise<IntegrationTools> {\n return buildLinearAgentTools({ requestContext: args.requestContext, linear: this });\n }\n\n /** Non-secret config snapshot for system diagnostics/startup logs. */\n diagnostics(): Record<string, unknown> {\n return {\n oauthAppConfigured: true,\n };\n }\n}\n\nfunction getLinearAccessToken(connection: IntegrationConnection): string {\n if (connection.type !== 'oauth') {\n throw new Error('Linear capabilities require an OAuth connection.');\n }\n return connection.accessToken;\n}\n\n/**\n * Self-managed source ids. Projects use their raw Linear project id (no prefix,\n * preserving existing intake bindings). Teams are prefixed so the two never\n * collide and callers can tell them apart.\n */\nconst SELF_MANAGED_TEAM_SOURCE_PREFIX = 'linear-team:';\n\nfunction encodeSelfManagedTeamSourceId(teamId: string): string {\n return `${SELF_MANAGED_TEAM_SOURCE_PREFIX}${teamId}`;\n}\n\nfunction isSelfManagedTeamSourceId(sourceId: string): boolean {\n return sourceId.startsWith(SELF_MANAGED_TEAM_SOURCE_PREFIX);\n}\n\nfunction decodeSelfManagedTeamSourceId(sourceId: string): string {\n return sourceId.slice(SELF_MANAGED_TEAM_SOURCE_PREFIX.length);\n}\n\n/**\n * Split selected source ids into raw project ids and raw team ids. A team\n * source id carries the `linear-team:` prefix; everything else is a project id.\n */\nfunction splitSelfManagedSourceIds(sourceIds: string[]): { projectIds: string[]; teamIds: string[] } {\n const projectIds: string[] = [];\n const teamIds: string[] = [];\n for (const sourceId of sourceIds) {\n if (isSelfManagedTeamSourceId(sourceId)) teamIds.push(decodeSelfManagedTeamSourceId(sourceId));\n else projectIds.push(sourceId);\n }\n return { projectIds, teamIds };\n}\n\ntype SelfManagedListCursor = {\n v: 1;\n sourceSet: string;\n projects: string | null;\n teams: string | null;\n};\n\nasync function linearSourceSetFingerprint(sourceIds: string[], attributionSourceIds: string[]): Promise<string> {\n const scope = {\n sourceIds: [...new Set(sourceIds)].sort(),\n attributionSourceIds: [...new Set(attributionSourceIds)].sort(),\n };\n const bytes = new TextEncoder().encode(JSON.stringify(scope));\n return Buffer.from(await globalThis.crypto.subtle.digest('SHA-256', bytes)).toString('base64url');\n}\n\nfunction invalidLinearCursor(): Error {\n return Object.assign(new Error('Linear cursor is invalid or stale.'), { code: 'invalid_cursor' as const });\n}\n\nfunction isCursorValue(value: unknown): value is string | null {\n return value === null || typeof value === 'string';\n}\n\nasync function decodeSelfManagedListCursor(\n cursor: string | undefined,\n sourceIds: string[],\n attributionSourceIds: string[],\n): Promise<{ projects: string | null | undefined; teams: string | null | undefined }> {\n const { projectIds, teamIds } = splitSelfManagedSourceIds(sourceIds);\n if (!cursor) {\n return {\n projects: projectIds.length > 0 ? undefined : null,\n teams: teamIds.length > 0 ? undefined : null,\n };\n }\n try {\n const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as Partial<SelfManagedListCursor>;\n if (\n parsed.v !== 1 ||\n parsed.sourceSet !== (await linearSourceSetFingerprint(sourceIds, attributionSourceIds)) ||\n !isCursorValue(parsed.projects) ||\n !isCursorValue(parsed.teams)\n ) {\n throw invalidLinearCursor();\n }\n return {\n projects: parsed.projects,\n teams: parsed.teams,\n };\n } catch {\n throw invalidLinearCursor();\n }\n}\n\nasync function encodeSelfManagedListCursor(\n state: Pick<SelfManagedListCursor, 'projects' | 'teams'>,\n sourceIds: string[],\n attributionSourceIds: string[],\n): Promise<string | null> {\n if (state.projects === null && state.teams === null) return null;\n return Buffer.from(\n JSON.stringify({\n v: 1,\n sourceSet: await linearSourceSetFingerprint(sourceIds, attributionSourceIds),\n ...state,\n } satisfies SelfManagedListCursor),\n ).toString('base64url');\n}\n\n/**\n * Deduplicate issues that surfaced from both a selected team and one of its\n * selected projects. Keeps one entry per Linear issue UUID.\n *\n * Tie-breaker — MOST-SPECIFIC-WINS: an issue in a selected project is\n * attributed to that project source (routes to the project's board); the team\n * source covers only the remainder (projectless issues and issues in projects\n * that were not separately selected). Change the comparison here to change the\n * routing policy — this is the single precedence point for the self-managed\n * integration, mirroring the platform-backed one.\n */\nfunction dedupeSelfManagedIssues(\n issues: Array<IntakeIssue & { sourceId?: string | null }>,\n): Array<IntakeIssue & { sourceId?: string | null }> {\n const isProjectSource = (sourceId: string | null | undefined): boolean =>\n typeof sourceId === 'string' && sourceId.length > 0 && !isSelfManagedTeamSourceId(sourceId);\n const winners = new Map<string, IntakeIssue & { sourceId?: string | null }>();\n for (const issue of issues) {\n const existing = winners.get(issue.id);\n if (!existing) {\n winners.set(issue.id, issue);\n continue;\n }\n // Project source beats team source; otherwise keep the first seen.\n if (isProjectSource(issue.sourceId) && !isProjectSource(existing.sourceId)) {\n winners.set(issue.id, issue);\n }\n }\n const seen = new Set<string>();\n const ordered: Array<IntakeIssue & { sourceId?: string | null }> = [];\n for (const issue of issues) {\n if (seen.has(issue.id)) continue;\n seen.add(issue.id);\n ordered.push(winners.get(issue.id)!);\n }\n return ordered;\n}\n\nfunction linearIssueToIntakeIssue(issue: Omit<LinearIssue, 'projectId'> & { projectId?: string | null }): IntakeIssue {\n return {\n id: issue.id,\n sourceId: issue.projectId ?? null,\n projectId: issue.projectId ?? null,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: issue.creator,\n state: issue.state,\n stateType: issue.stateType,\n priority: issue.priorityLabel,\n assignee: issue.assignee,\n source: issue.team,\n labels: issue.labels,\n commentCount: null,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n"],"mappings":";;;;;;;;AAgDA,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AA6G7B,MAAM,0BAA0B;AAChC,MAAM,2BAA2B;AACjC,MAAM,yBAAyB;AAC/B,MAAM,yBAAyB;;AAE/B,MAAM,2BAA2B;;AAGjC,MAAM,wBAAwB;;AAG9B,MAAM,oBAAoB;AAE1B,MAAM,eAAe;;AAGrB,IAAa,4BAAb,cAA+C,MAAM;CACnD,cAAc;EACZ,MAAM,+EAA+E;CACvF;AACF;;AA2EA,eAAe,cAAiB,aAAqB,OAAe,WAAiD;CACnH,MAAM,MAAM,MAAM,MAAM,oBAAoB;EAC1C,QAAQ;EACR,QAAQ,YAAY,QAAQ,IAAM;EAClC,SAAS;GACP,gBAAgB;GAChB,eAAe,UAAU;EAC3B;EACA,MAAM,KAAK,UAAU;GAAE;GAAO;EAAU,CAAC;CAC3C,CAAC;CACD,IAAI,CAAC,IAAI,IAAI;EAGX,IAAI,SAAwB;EAC5B,IAAI;GAEF,UAAS,MADc,IAAI,KAAK,EAAA,CACf,SAAS,EAAE,EAAE,WAAW;EAC3C,QAAQ,CAER;EACA,MAAM,sBAAM,IAAI,MAAM,8BAA8B,IAAI,OAAO,GAAG,SAAS,KAAK,WAAW,IAAI;EAC/F,IAA6B,SAAS,IAAI;EAC1C,MAAM;CACR;CACA,MAAM,OAAQ,MAAM,IAAI,KAAK;CAC7B,IAAI,KAAK,QAAQ,QACf,MAAM,IAAI,MAAM,qBAAqB,KAAK,OAAO,EAAE,EAAE,WAAW,iBAAiB;CAEnF,IAAI,CAAC,KAAK,MACR,MAAM,IAAI,MAAM,8BAA8B;CAEhD,OAAO,KAAK;AACd;AAEA,IAAa,oBAAb,MAA6D;;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AC,SAAS,WAAW;AACxB;;;;;;;;;;;;AAaA,SAAS,wBACP,QACmD;CACnD,MAAM,mBAAmB,aACvB,OAAO,aAAa,YAAY,SAAS,SAAS,KAAK,CAAC,0BAA0B,QAAQ;CAC5F,MAAM,0BAAU,IAAI,IAAwD;CAC5E,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,QAAQ,IAAI,MAAM,EAAE;EACrC,IAAI,CAAC,UAAU;GACb,QAAQ,IAAI,MAAM,IAAI,KAAK;GAC3B;EACF;EAEA,IAAI,gBAAgB,MAAM,QAAQ,KAAK,CAAC,gBAAgB,SAAS,QAAQ,GACvE,QAAQ,IAAI,MAAM,IAAI,KAAK;CAE/B;CACA,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,UAA6D,CAAC;CACpE,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,KAAK,IAAI,MAAM,EAAE,GAAG;EACxB,KAAK,IAAI,MAAM,EAAE;EACjB,QAAQ,KAAK,QAAQ,IAAI,MAAM,EAAE,CAAE;CACrC;CACA,OAAO;AACT;AAEA,SAAS,yBAAyB,OAAoF;CACpH,OAAO;EACL,IAAI,MAAM;EACV,UAAU,MAAM,aAAa;EAC7B,WAAW,MAAM,aAAa;EAC9B,YAAY,MAAM;EAClB,OAAO,MAAM;EACb,KAAK,MAAM;EACX,QAAQ,MAAM;EACd,OAAO,MAAM;EACb,WAAW,MAAM;EACjB,UAAU,MAAM;EAChB,UAAU,MAAM;EAChB,QAAQ,MAAM;EACd,QAAQ,MAAM;EACd,cAAc;EACd,WAAW,MAAM;EACjB,WAAW,MAAM;CACnB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-worker.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/github/event-worker.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"event-worker.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/github/event-worker.ts"],"names":[],"mappings":"AAAA,O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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"}
|
|
@@ -2,7 +2,6 @@ import { listPullRequestSubscriptionsForWebhook, retirePullRequestSubscription }
|
|
|
2
2
|
import { PlatformApiError } from "../api-client.js";
|
|
3
3
|
import { dispatchGithubWebhook, isFactoryAppSender, resolveAuthorizedBots } from "../../github/webhook.js";
|
|
4
4
|
import { NoopLeaseProvider, isLeaseProvider } from "@mastra/core/events";
|
|
5
|
-
import { randomUUID } from "crypto";
|
|
6
5
|
import { MastraWorker } from "@mastra/core/worker";
|
|
7
6
|
//#region src/integrations/platform/github/event-worker.ts
|
|
8
7
|
const API_PREFIX = "/v1/server/github-app";
|
|
@@ -50,7 +49,7 @@ var PlatformGithubEventWorker = class extends MastraWorker {
|
|
|
50
49
|
#now;
|
|
51
50
|
#dispatch;
|
|
52
51
|
#sourceControl;
|
|
53
|
-
#leaseOwner = randomUUID();
|
|
52
|
+
#leaseOwner = globalThis.crypto.randomUUID();
|
|
54
53
|
#running = false;
|
|
55
54
|
#timer;
|
|
56
55
|
#leaseRenewalTimer;
|
|
@@ -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', {\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;EACh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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 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 = globalThis.crypto.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":";;;;;;AAqBA,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,OAAO,WAAW;CAEpD,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,kCAAkC,OAAO,kCAAkC;EAChF,KAAKC,4BAA4B,OAAO,4BAA4B;EACpE,KAAKC,cAAc,OAAO,cAAc;EACxC,IAAI,CAAC,OAAO,SAAS,KAAKA,WAAW,KAAK,KAAKA,eAAe,GAC5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ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"event-worker.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/gitlab/event-worker.ts"],"names":[],"mappings":"AAAA,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;AAC9F,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EAA0B,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACvF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AACnE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAgB1D,KAAK,iCAAiC,GAAG;IACvC,OAAO,EAAE,CAAC,CAAC;IACX,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACvD,CAAC;AAEF,MAAM,MAAM,0BAA0B,GAAG,wBAAwB,CAC/D,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACvB,iCAAiC,EACjC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CACxB,CAAC;AAEF,qDAAqD;AACrD,MAAM,WAAW,qBAAqB;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,6BAA6B;IAC5C,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,QAAQ,GAAG,cAAc,CAAC;CACnC;AAED,MAAM,MAAM,sCAAsC,GAAG,gCAAgC,CAAC;AAEtF,MAAM,WAAW,+BAA+B;IAC9C,MAAM,EAAE,iBAAiB,CAAC;IAC1B,UAAU,EAAE,iBAAiB,CAAC,YAAY,CAAC,CAAC;IAC5C,MAAM,EAAE,sCAAsC,CAAC;IAC/C,OAAO,EAAE,0BAA0B,CAAC;IACpC,mEAAmE;IACnE,eAAe,EAAE,MAAM,OAAO,CAAC,6BAA6B,EAAE,CAAC,CAAC;IAChE,kBAAkB,CAAC,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACtE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,oBAAoB,CAAC;CACvC;AAED;;;;;;;;;;;GAWG;AACH,qBAAa,yBAA0B,SAAQ,YAAY;;IACzD,QAAQ,CAAC,IAAI,4BAA4B;gBAuB7B,MAAM,EAAE,+BAA+B;IAiB7C,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;CAiOF"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { PlatformApiError } from "../api-client.js";
|
|
2
2
|
import { parseGitLabWebhookBody, processGitLabWebhook } from "../../gitlab/webhook.js";
|
|
3
3
|
import { NoopLeaseProvider, isLeaseProvider } from "@mastra/core/events";
|
|
4
|
-
import { randomUUID } from "crypto";
|
|
5
4
|
import { MastraWorker } from "@mastra/core/worker";
|
|
6
5
|
//#region src/integrations/platform/gitlab/event-worker.ts
|
|
7
6
|
const DEFAULT_POLL_INTERVAL_MS = 2e4;
|
|
@@ -39,7 +38,7 @@ var PlatformGitLabEventWorker = class extends MastraWorker {
|
|
|
39
38
|
#intervalMs;
|
|
40
39
|
#now;
|
|
41
40
|
#process;
|
|
42
|
-
#leaseOwner = randomUUID();
|
|
41
|
+
#leaseOwner = globalThis.crypto.randomUUID();
|
|
43
42
|
#running = false;
|
|
44
43
|
#timer;
|
|
45
44
|
#leaseRenewalTimer;
|