@mastra/factory 0.2.0 → 0.2.1-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/dist/capabilities/intake.d.ts +45 -0
- package/dist/capabilities/intake.d.ts.map +1 -1
- package/dist/factory.js +920 -549
- package/dist/factory.js.map +1 -1
- package/dist/index.js +920 -549
- package/dist/index.js.map +1 -1
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +126 -11
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/project-lock.d.ts +24 -2
- package/dist/integrations/github/project-lock.d.ts.map +1 -1
- package/dist/integrations/github/project-lock.js +43 -10
- package/dist/integrations/github/project-lock.js.map +1 -1
- package/dist/integrations/github/routes.js +41 -10
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/linear/agent-tools.js.map +1 -1
- package/dist/integrations/linear/integration.d.ts.map +1 -1
- package/dist/integrations/linear/integration.js +60 -1
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +7 -1
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +104 -12
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +91 -0
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/routes/fs.d.ts +16 -0
- package/dist/routes/fs.d.ts.map +1 -1
- package/dist/routes/fs.js +103 -3
- package/dist/routes/fs.js.map +1 -1
- package/dist/routes/oauth.js +564 -478
- package/dist/routes/oauth.js.map +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +1 -0
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +717 -526
- package/dist/routes/surface.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +0 -1
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +6 -7
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/integrations/linear/agent-tools.ts","../../../src/integrations/linear/routes.ts","../../../src/integrations/linear/integration.ts"],"sourcesContent":["/**\n * Linear tools exposed to the coding agent.\n *\n * Wired into the agent through the SDK's async `extraTools` provider: on each\n * tool-set resolution we map the session's resourceId (the factory project id)\n * to its owning org and only expose the Linear tools when that org has a\n * Linear connection. Projects whose org never connected Linear (or when the\n * feature is disabled) see no Linear tools at all — the model is never shown\n * tools it can't use.\n *\n * Tenancy mirrors the Linear API routes: everything is scoped by the org that\n * owns the project, and tokens are refreshed through the integration's shared\n * connection lifecycle.\n */\n\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { LinearIntegration } from './integration.js';\nimport { LinearReauthRequiredError } from './integration.js';\n\nfunction createLinearGetIssueTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_get_issue',\n description:\n \"Fetch a Linear issue's full details — title, description, state, assignee, labels, priority, and discussion comments. Use this whenever you're working on a Linear issue (e.g. ENG-123) to get its complete context.\",\n inputSchema: z.object({\n issue: z.string().min(1).describe('The Linear issue identifier (e.g. \"ENG-123\") or issue UUID.'),\n }),\n execute: async ({ issue }: { issue: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to fetch issues.' };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const detail = await linear.intake.getIssue({\n connection: { type: 'oauth', accessToken },\n issueId: issue.trim(),\n });\n if (!detail) {\n return { error: `Linear issue \"${issue}\" was not found in this workspace.` };\n }\n return detail;\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to fetch Linear issue: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\nfunction createLinearCommentTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_create_comment',\n description:\n 'Post a comment on a Linear issue (e.g. to report investigation findings, link a PR, or ask a clarifying question). The comment is posted as the connected Linear integration, so make clear it comes from the agent.',\n inputSchema: z.object({\n issue: z.string().min(1).describe('The Linear issue identifier (e.g. \"ENG-123\") or issue UUID.'),\n body: z.string().min(1).describe('The comment body, as Linear-flavored markdown.'),\n }),\n execute: async ({ issue, body }: { issue: string; body: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to post comments.' };\n }\n if (!linear.canPostComments(connection)) {\n return {\n error: 'The Linear connection does not have comment permissions. Reconnect Linear in Settings to grant them.',\n };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const comment = await linear.intake.createComment({\n connection: { type: 'oauth', accessToken },\n issueId: issue.trim(),\n body,\n });\n if (!comment) {\n return { error: `Linear issue \"${issue}\" was not found in this workspace.` };\n }\n return { posted: true, url: comment.url };\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to post Linear comment: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\n/**\n * Async `extraTools` provider: expose Linear tools only when the session's\n * project belongs to an org with an active Linear connection.\n */\nexport async function buildLinearAgentTools({\n requestContext,\n linear,\n}: {\n requestContext: RequestContext;\n /** The integration instance providing the Linear API client. */\n linear: LinearIntegration;\n}): Promise<Record<string, ReturnType<typeof createLinearGetIssueTool> | ReturnType<typeof createLinearCommentTool>>> {\n if (!linear.authEnabled) return {};\n\n const ctx = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n const resourceId = ctx?.resourceId;\n if (!resourceId) return {};\n\n const orgId = await linear.resolveOrgId(resourceId);\n if (!orgId) return {};\n const check = await linear.checkConnection(orgId);\n if (!check.connected) return {};\n\n return {\n linear_get_issue: createLinearGetIssueTool(linear, orgId),\n // Only offered when the granted OAuth scope allows posting comments —\n // connections made before `comments:create` was requested are read-only\n // until the org reconnects Linear.\n ...(check.canComment ? { linear_create_comment: createLinearCommentTool(linear, orgId) } : {}),\n };\n}\n","/**\n * Mastra `apiRoutes` for the Linear intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the WorkOS auth gate.\n * Mirrors the GitHub module: every route re-resolves the authenticated user\n * from the request cookie and scopes all rows by the caller's WorkOS org, so an\n * org can only ever see its own Linear connection and issues.\n *\n * When the feature is disabled (`isLinearFeatureEnabled()` false),\n * `buildLinearRoutes` returns only `GET /web/linear/status`, which reports\n * `enabled:false` so the SPA can cleanly hide all Linear UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { StateSigner } from '../../state-signing.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { IntegrationHooks } from '../base.js';\nimport type { LinearIntegration } from './integration.js';\nimport { LinearReauthRequiredError } from './integration.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\n\n/**\n * Non-secret diagnostic snapshot of every Linear feature gate, mirroring the\n * GitHub diagnostics shape. Only booleans — never values.\n */\nexport interface LinearFeatureDiagnostics {\n linearAppConfigured: boolean;\n factoryAuthEnabled: boolean;\n appDbConfigured: boolean;\n}\n\nexport interface MountLinearRoutesOptions {\n /**\n * The integration instance providing OAuth + GraphQL access. Required for\n * everything beyond the disabled `status` route.\n */\n linear?: LinearIntegration;\n /** Host auth seam. Linear connections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Absolute base URL of the web server (e.g. `http://localhost:4111`), used to\n * build the OAuth redirect URI when one isn't explicitly configured.\n */\n baseUrl?: string;\n /** Explicit OAuth callback URI; defaults to `<baseUrl>/auth/linear/callback`. */\n redirectUri?: string;\n /**\n * Shared OAuth `state` signer (created once per boot by the factory).\n * Required for the connect/callback flow; when absent, only the disabled\n * `status` route is served.\n */\n stateSigner?: StateSigner;\n /**\n * Cross-integration intake selection domain. Required for the issues route's\n * project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\n hooks?: IntegrationHooks;\n}\n\n/**\n * Resolve the org-scoped tenant for a Linear request. The connection is\n * org-owned, so it requires both a signed-in user and an organization — same\n * tenancy rules as the GitHub routes.\n */\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Linear intake requires an organization. Personal accounts cannot connect Linear.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque Linear pagination cursor from the query string. Cursors\n * are server-issued (`pageInfo.endCursor`), so anything outside a conservative\n * charset/length is rejected rather than forwarded to Linear.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 512 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map a Linear read failure to the API response for the SPA. */\nfunction linearFetchError(c: RouteContext, err: unknown) {\n if (err instanceof LinearReauthRequiredError || (err as { status?: number }).status === 401) {\n return c.json({ error: 'linear_reauth_required', message: new LinearReauthRequiredError().message }, 409);\n }\n return c.json({ error: 'linear_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the Linear routes as Mastra `apiRoutes`. When the feature is disabled,\n * returns only the `status` route so the SPA can detect the disabled state.\n */\nexport function buildLinearRoutes(options: MountLinearRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { linear, auth, stateSigner, intake } = options;\n const enabled = Boolean(linear) && auth.enabled();\n const diagnostics = (): LinearFeatureDiagnostics => ({\n linearAppConfigured: Boolean(linear),\n factoryAuthEnabled: auth.enabled(),\n appDbConfigured: true,\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !linear || !stateSigner) {\n return c.json({\n enabled: false,\n connected: false,\n workspace: null,\n reason: 'missing_config',\n diagnostics: diagnostics(),\n });\n }\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n organizationRequired: true,\n connected: false,\n workspace: null,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n const connection = await linear.loadConnection(tenant.orgId);\n return c.json({\n enabled: true,\n connected: Boolean(connection),\n workspace: connection ? { name: connection.workspaceName, urlKey: connection.workspaceUrlKey } : null,\n reason: connection ? 'ready' : 'not_connected',\n diagnostics: diagnostics(),\n });\n },\n }),\n );\n\n // Without the integration instance or a state signer the connect/callback\n // flow cannot talk to Linear or bind the OAuth round-trip to a tenant —\n // serve only the disabled `status` route (mirrors the feature gate).\n if (!enabled || !linear || !stateSigner || !intake) {\n return routes;\n }\n\n const redirectUri = options.redirectUri ?? `${(options.baseUrl ?? '').replace(/\\/$/, '')}/auth/linear/callback`;\n\n // ── Connect: send the user to Linear's OAuth consent screen ─────────────\n routes.push(\n registerApiRoute('/auth/linear/connect', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n const state = stateSigner.sign(resolved.tenant.orgId, resolved.tenant.userId);\n return c.redirect(linear.buildAuthorizeUrl(state, redirectUri));\n },\n }),\n );\n\n // ── Callback: exchange the code, persist the connection for the org ─────\n routes.push(\n registerApiRoute('/auth/linear/callback', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n const { orgId, userId } = resolved.tenant;\n\n // CSRF / cross-tenant linking protection: the signed state must belong\n // to the same logged-in user *and* their current org.\n const stateTenant = stateSigner.verify(c.req.query('state'));\n if (!stateTenant || stateTenant.userId !== userId || stateTenant.orgId !== orgId) {\n console.warn('[Linear] OAuth callback rejected: state/tenant mismatch.');\n return c.redirect('/?linear=error');\n }\n\n const code = c.req.query('code');\n if (!code) {\n // User denied consent (or Linear returned an error).\n return c.redirect('/?linear=error');\n }\n\n try {\n const tokens = await linear.exchangeOAuthCode(code, redirectUri);\n const workspace = await linear.fetchWorkspace(tokens.accessToken);\n await linear.upsertConnection({\n orgId,\n userId,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresAt,\n scope: tokens.scope,\n workspaceName: workspace.name,\n workspaceUrlKey: workspace.urlKey,\n });\n } catch (error) {\n console.warn(`[Linear] OAuth callback failed to persist connection for org ${orgId}.`, error);\n return c.redirect('/?linear=error');\n }\n\n return c.redirect('/?linear=connected');\n },\n }),\n );\n\n // ── List the workspace's projects (Settings intake-source picker) ───────\n routes.push(\n registerApiRoute('/web/linear/projects', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to list Linear projects.' }, 409);\n }\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const projects = await linear.listProjects(accessToken);\n return c.json({ projects });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the workspace's active issues (cursor-paged) ───────────────────\n // Respects the caller's intake config: disabled Linear intake 404s the\n // source, and an explicit project selection narrows the issue filter.\n routes.push(\n registerApiRoute('/web/linear/issues', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const after = parseAfterCursor(c.req.query('after'));\n if (after === null) return c.json({ error: 'invalid_cursor' }, 400);\n const factoryProjectId = c.req.query('factoryProjectId');\n if (factoryProjectId && !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n\n const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to see intake issues.' }, 409);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n integrationIds: ['linear'],\n });\n const selection = config.linear!;\n if (!selection.enabled) {\n return c.json({ error: 'linear_intake_disabled', message: 'Linear intake is turned off in Settings.' }, 404);\n }\n\n // No projects selected means nothing is synced — don't fan out to Linear.\n const projectIds = selection.sourceIds ?? [];\n if (projectIds.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const { issues, nextCursor } = await linear.intake.listIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds: projectIds,\n cursor: after,\n });\n const issuePayload = issues.map(issue => ({\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee,\n team: issue.source,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n }));\n if (factoryProjectId && options.hooks?.ingestLinearIssues) {\n await options.hooks.ingestLinearIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n });\n }\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n","/**\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';\n\nimport type { IntegrationConnection } from '../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n ListIntakeIssuesInput,\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 { buildLinearAgentTools } from './agent-tools.js';\nimport { buildLinearRoutes } from './routes.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 for the Linear OAuth application. All fields are required. */\nexport interface LinearIntegrationConfig {\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;\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 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\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;\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 };\n assignee: { name: string } | null;\n team: { 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 };\n assignee: { name: string } | null;\n team: { 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 listSources: async ({ orgId }) => {\n const connection = await this.loadConnection(orgId);\n if (!connection) return [];\n const accessToken = await this.getFreshAccessToken(connection);\n const projects = await this.listProjects(accessToken);\n return projects.map(project => ({\n id: project.id,\n name: project.name,\n type: 'project',\n }));\n },\n listItems: async ({ orgId, sourceIds, 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.listActiveIssues(accessToken, cursor, sourceIds);\n return {\n items: page.issues.map(issue => ({\n source: { type: 'issue', externalId: issue.id, url: issue.url },\n sourceId: issue.projectId,\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 stateType: issue.stateType,\n priority: issue.priorityLabel,\n team: issue.team,\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 };\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 constructor(config: LinearIntegrationConfig) {\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 const result = await this.listActiveIssues(accessToken, input.cursor, input.sourceIds, input.labels);\n return {\n issues: result.issues.map(issue => linearIssueToIntakeIssue(issue)),\n nextCursor: result.nextCursor,\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 /** 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 /**\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.\n */\n async listActiveIssues(\n accessToken: string,\n after?: string,\n projectIds?: string[],\n labels?: 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 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}${labelVar}) {\n issues(\n first: $first\n after: $after\n orderBy: updatedAt\n filter: { state: { type: { in: [\"triage\", \"backlog\", \"unstarted\", \"started\"] } }${projectFilter}${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 team { 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 ...(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,\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 team: node.team?.key ?? null,\n labels: node.labels.nodes.map(label => label.name),\n createdAt: node.createdAt,\n updatedAt: node.updatedAt,\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 ({ 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(accessToken: string, idOrIdentifier: string): 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 team { 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,\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 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 /**\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 hooks: ctx.hooks,\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\nfunction linearIssueToIntakeIssue(issue: LinearIssue): IntakeIssue {\n return {\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: null,\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":";AAiBA,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAKlB,SAAS,yBAAyB,QAA2B,OAAe;AAC1E,SAAO,WAAW;AAAA,IAChB,IAAI;AAAA,IACJ,aACE;AAAA,IACF,aAAa,EAAE,OAAO;AAAA,MACpB,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,6DAA6D;AAAA,IACjG,CAAC;AAAA,IACD,SAAS,OAAO,EAAE,MAAM,MAAyB;AAC/C,YAAM,aAAa,MAAM,OAAO,eAA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A,IAChB,QAAQ,MAAM;AAAA,IACd,QAAQ,MAAM;AAAA,IACd,cAAc;AAAA,IACd,WAAW,MAAM;AAAA,IACjB,WAAW,MAAM;AAAA,EACnB;AACF;","names":["data"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/integrations/linear/agent-tools.ts","../../../src/integrations/linear/routes.ts","../../../src/integrations/linear/integration.ts"],"sourcesContent":["/**\n * Linear tools exposed to the coding agent.\n *\n * Wired into the agent through the SDK's async `extraTools` provider: on each\n * tool-set resolution we map the session's resourceId (the factory project id)\n * to its owning org and only expose the Linear tools when that org has a\n * Linear connection. Projects whose org never connected Linear (or when the\n * feature is disabled) see no Linear tools at all — the model is never shown\n * tools it can't use.\n *\n * Tenancy mirrors the Linear API routes: everything is scoped by the org that\n * owns the project, and tokens are refreshed through the integration's shared\n * connection lifecycle.\n */\n\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { LinearIntegration } from './integration.js';\nimport { LinearReauthRequiredError } from './integration.js';\n\nfunction createLinearGetIssueTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_get_issue',\n description:\n \"Fetch a Linear issue's full details — title, description, state, assignee, labels, priority, and discussion comments. Use this whenever you're working on a Linear issue (e.g. ENG-123) to get its complete context.\",\n inputSchema: z.object({\n issue: z.string().min(1).describe('The Linear issue identifier (e.g. \"ENG-123\") or issue UUID.'),\n }),\n execute: async ({ issue }: { issue: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to fetch issues.' };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const detail = await linear.intake.getIssue({\n connection: { type: 'oauth', accessToken },\n issueId: issue.trim(),\n });\n if (!detail) {\n return { error: `Linear issue \"${issue}\" was not found in this workspace.` };\n }\n return detail;\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to fetch Linear issue: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\nfunction createLinearCommentTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_create_comment',\n description:\n 'Post a comment on a Linear issue (e.g. to report investigation findings, link a PR, or ask a clarifying question). The comment is posted as the connected Linear integration, so make clear it comes from the agent.',\n inputSchema: z.object({\n issue: z.string().min(1).describe('The Linear issue identifier (e.g. \"ENG-123\") or issue UUID.'),\n body: z.string().min(1).describe('The comment body, as Linear-flavored markdown.'),\n }),\n execute: async ({ issue, body }: { issue: string; body: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to post comments.' };\n }\n if (!linear.canPostComments(connection)) {\n return {\n error: 'The Linear connection does not have comment permissions. Reconnect Linear in Settings to grant them.',\n };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const comment = await linear.intake.createComment({\n connection: { type: 'oauth', accessToken },\n issueId: issue.trim(),\n body,\n });\n if (!comment) {\n return { error: `Linear issue \"${issue}\" was not found in this workspace.` };\n }\n return { posted: true, url: comment.url };\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to post Linear comment: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\n/**\n * Async `extraTools` provider: expose Linear tools only when the session's\n * project belongs to an org with an active Linear connection.\n */\nexport async function buildLinearAgentTools({\n requestContext,\n linear,\n}: {\n requestContext: RequestContext;\n /** The integration instance providing the Linear API client. */\n linear: LinearIntegration;\n}): Promise<Record<string, ReturnType<typeof createLinearGetIssueTool> | ReturnType<typeof createLinearCommentTool>>> {\n if (!linear.authEnabled) return {};\n\n const ctx = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n const resourceId = ctx?.resourceId;\n if (!resourceId) return {};\n\n const orgId = await linear.resolveOrgId(resourceId);\n if (!orgId) return {};\n const check = await linear.checkConnection(orgId);\n if (!check.connected) return {};\n\n return {\n linear_get_issue: createLinearGetIssueTool(linear, orgId),\n // Only offered when the granted OAuth scope allows posting comments —\n // connections made before `comments:create` was requested are read-only\n // until the org reconnects Linear.\n ...(check.canComment ? { linear_create_comment: createLinearCommentTool(linear, orgId) } : {}),\n };\n}\n","/**\n * Mastra `apiRoutes` for the Linear intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the WorkOS auth gate.\n * Mirrors the GitHub module: every route re-resolves the authenticated user\n * from the request cookie and scopes all rows by the caller's WorkOS org, so an\n * org can only ever see its own Linear connection and issues.\n *\n * When the feature is disabled (`isLinearFeatureEnabled()` false),\n * `buildLinearRoutes` returns only `GET /web/linear/status`, which reports\n * `enabled:false` so the SPA can cleanly hide all Linear UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { StateSigner } from '../../state-signing.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { IntegrationHooks } from '../base.js';\nimport type { LinearIntegration } from './integration.js';\nimport { LinearReauthRequiredError } from './integration.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\n\n/**\n * Non-secret diagnostic snapshot of every Linear feature gate, mirroring the\n * GitHub diagnostics shape. Only booleans — never values.\n */\nexport interface LinearFeatureDiagnostics {\n linearAppConfigured: boolean;\n factoryAuthEnabled: boolean;\n appDbConfigured: boolean;\n}\n\nexport interface MountLinearRoutesOptions {\n /**\n * The integration instance providing OAuth + GraphQL access. Required for\n * everything beyond the disabled `status` route.\n */\n linear?: LinearIntegration;\n /** Host auth seam. Linear connections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Absolute base URL of the web server (e.g. `http://localhost:4111`), used to\n * build the OAuth redirect URI when one isn't explicitly configured.\n */\n baseUrl?: string;\n /** Explicit OAuth callback URI; defaults to `<baseUrl>/auth/linear/callback`. */\n redirectUri?: string;\n /**\n * Shared OAuth `state` signer (created once per boot by the factory).\n * Required for the connect/callback flow; when absent, only the disabled\n * `status` route is served.\n */\n stateSigner?: StateSigner;\n /**\n * Cross-integration intake selection domain. Required for the issues route's\n * project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\n hooks?: IntegrationHooks;\n}\n\n/**\n * Resolve the org-scoped tenant for a Linear request. The connection is\n * org-owned, so it requires both a signed-in user and an organization — same\n * tenancy rules as the GitHub routes.\n */\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Linear intake requires an organization. Personal accounts cannot connect Linear.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque Linear pagination cursor from the query string. Cursors\n * are server-issued (`pageInfo.endCursor`), so anything outside a conservative\n * charset/length is rejected rather than forwarded to Linear.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 512 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map a Linear read failure to the API response for the SPA. */\nfunction linearFetchError(c: RouteContext, err: unknown) {\n if (err instanceof LinearReauthRequiredError || (err as { status?: number }).status === 401) {\n return c.json({ error: 'linear_reauth_required', message: new LinearReauthRequiredError().message }, 409);\n }\n return c.json({ error: 'linear_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the Linear routes as Mastra `apiRoutes`. When the feature is disabled,\n * returns only the `status` route so the SPA can detect the disabled state.\n */\nexport function buildLinearRoutes(options: MountLinearRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { linear, auth, stateSigner, intake } = options;\n const enabled = Boolean(linear) && auth.enabled();\n const diagnostics = (): LinearFeatureDiagnostics => ({\n linearAppConfigured: Boolean(linear),\n factoryAuthEnabled: auth.enabled(),\n appDbConfigured: true,\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !linear || !stateSigner) {\n return c.json({\n enabled: false,\n connected: false,\n workspace: null,\n reason: 'missing_config',\n diagnostics: diagnostics(),\n });\n }\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n organizationRequired: true,\n connected: false,\n workspace: null,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n const connection = await linear.loadConnection(tenant.orgId);\n return c.json({\n enabled: true,\n connected: Boolean(connection),\n workspace: connection ? { name: connection.workspaceName, urlKey: connection.workspaceUrlKey } : null,\n reason: connection ? 'ready' : 'not_connected',\n diagnostics: diagnostics(),\n });\n },\n }),\n );\n\n // Without the integration instance or a state signer the connect/callback\n // flow cannot talk to Linear or bind the OAuth round-trip to a tenant —\n // serve only the disabled `status` route (mirrors the feature gate).\n if (!enabled || !linear || !stateSigner || !intake) {\n return routes;\n }\n\n const redirectUri = options.redirectUri ?? `${(options.baseUrl ?? '').replace(/\\/$/, '')}/auth/linear/callback`;\n\n // ── Connect: send the user to Linear's OAuth consent screen ─────────────\n routes.push(\n registerApiRoute('/auth/linear/connect', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n const state = stateSigner.sign(resolved.tenant.orgId, resolved.tenant.userId);\n return c.redirect(linear.buildAuthorizeUrl(state, redirectUri));\n },\n }),\n );\n\n // ── Callback: exchange the code, persist the connection for the org ─────\n routes.push(\n registerApiRoute('/auth/linear/callback', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n const { orgId, userId } = resolved.tenant;\n\n // CSRF / cross-tenant linking protection: the signed state must belong\n // to the same logged-in user *and* their current org.\n const stateTenant = stateSigner.verify(c.req.query('state'));\n if (!stateTenant || stateTenant.userId !== userId || stateTenant.orgId !== orgId) {\n console.warn('[Linear] OAuth callback rejected: state/tenant mismatch.');\n return c.redirect('/?linear=error');\n }\n\n const code = c.req.query('code');\n if (!code) {\n // User denied consent (or Linear returned an error).\n return c.redirect('/?linear=error');\n }\n\n try {\n const tokens = await linear.exchangeOAuthCode(code, redirectUri);\n const workspace = await linear.fetchWorkspace(tokens.accessToken);\n await linear.upsertConnection({\n orgId,\n userId,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresAt,\n scope: tokens.scope,\n workspaceName: workspace.name,\n workspaceUrlKey: workspace.urlKey,\n });\n } catch (error) {\n console.warn(`[Linear] OAuth callback failed to persist connection for org ${orgId}.`, error);\n return c.redirect('/?linear=error');\n }\n\n return c.redirect('/?linear=connected');\n },\n }),\n );\n\n // ── List the workspace's projects (Settings intake-source picker) ───────\n routes.push(\n registerApiRoute('/web/linear/projects', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to list Linear projects.' }, 409);\n }\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const projects = await linear.listProjects(accessToken);\n return c.json({ projects });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the workspace's active issues (cursor-paged) ───────────────────\n // Respects the caller's intake config: disabled Linear intake 404s the\n // source, and an explicit project selection narrows the issue filter.\n routes.push(\n registerApiRoute('/web/linear/issues', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const after = parseAfterCursor(c.req.query('after'));\n if (after === null) return c.json({ error: 'invalid_cursor' }, 400);\n const factoryProjectId = c.req.query('factoryProjectId');\n if (factoryProjectId && !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n\n const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to see intake issues.' }, 409);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n integrationIds: ['linear'],\n });\n const selection = config.linear!;\n if (!selection.enabled) {\n return c.json({ error: 'linear_intake_disabled', message: 'Linear intake is turned off in Settings.' }, 404);\n }\n\n // No projects selected means nothing is synced — don't fan out to Linear.\n const projectIds = selection.sourceIds ?? [];\n if (projectIds.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const { issues, nextCursor } = await linear.intake.listIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds: projectIds,\n cursor: after,\n });\n const issuePayload = issues.map(issue => ({\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee,\n team: issue.source,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n }));\n if (factoryProjectId && options.hooks?.ingestLinearIssues) {\n await options.hooks.ingestLinearIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n });\n }\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n","/**\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';\n\nimport type { IntegrationConnection } from '../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n ListIntakeIssuesInput,\n UpdateIntakeIssueInput,\n} from '../../capabilities/intake.js';\nimport type { 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 { buildLinearAgentTools } from './agent-tools.js';\nimport { buildLinearRoutes } from './routes.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 for the Linear OAuth application. All fields are required. */\nexport interface LinearIntegrationConfig {\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;\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 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\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;\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 };\n assignee: { name: string } | null;\n team: { 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 };\n assignee: { name: string } | null;\n team: { 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 = await this.listProjects(accessToken);\n return projects.map(project => ({\n id: project.id,\n name: project.name,\n type: 'project',\n }));\n },\n listItems: async ({ orgId, sourceIds, 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.listActiveIssues(accessToken, cursor, sourceIds);\n return {\n items: page.issues.map(issue => ({\n source: { type: 'issue', externalId: issue.id, url: issue.url },\n sourceId: issue.projectId,\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 stateType: issue.stateType,\n priority: issue.priorityLabel,\n team: issue.team,\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 constructor(config: LinearIntegrationConfig) {\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 const result = await this.listActiveIssues(accessToken, input.cursor, input.sourceIds, input.labels);\n return {\n issues: result.issues.map(issue => linearIssueToIntakeIssue(issue)),\n nextCursor: result.nextCursor,\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 /**\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.\n */\n async listActiveIssues(\n accessToken: string,\n after?: string,\n projectIds?: string[],\n labels?: 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 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}${labelVar}) {\n issues(\n first: $first\n after: $after\n orderBy: updatedAt\n filter: { state: { type: { in: [\"triage\", \"backlog\", \"unstarted\", \"started\"] } }${projectFilter}${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 team { 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 ...(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,\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 team: node.team?.key ?? null,\n labels: node.labels.nodes.map(label => label.name),\n createdAt: node.createdAt,\n updatedAt: node.updatedAt,\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 ({ 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(accessToken: string, idOrIdentifier: string): 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 team { 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,\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 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 /**\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 hooks: ctx.hooks,\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\nfunction linearIssueToIntakeIssue(issue: LinearIssue): IntakeIssue {\n return {\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: null,\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":";AAiBA,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAKlB,SAAS,yBAAyB,QAA2B,OAAe;AAC1E,SAAO,WAAW;AAAA,IAChB,IAAI;AAAA,IACJ,aACE;AAAA,IACF,aAAa,EAAE,OAAO;AAAA,MACpB,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,6DAA6D;AAAA,IACjG,CAAC;AAAA,IACD,SAAS,OAAO,EAAE,MAAM,MAAyB;AAC/C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