@mastra/factory 0.16.0-alpha.7 → 0.16.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +2 -2
  2. package/dist/boards/work.d.ts.map +1 -1
  3. package/dist/boards/work.js +18 -1
  4. package/dist/boards/work.js.map +1 -1
  5. package/dist/factory.d.ts +3 -2
  6. package/dist/factory.d.ts.map +1 -1
  7. package/dist/factory.js +3 -2
  8. package/dist/factory.js.map +1 -1
  9. package/dist/integrations/base.d.ts +2 -0
  10. package/dist/integrations/base.d.ts.map +1 -1
  11. package/dist/integrations/incidentio/agent-tools.d.ts +49 -0
  12. package/dist/integrations/incidentio/agent-tools.d.ts.map +1 -0
  13. package/dist/integrations/incidentio/agent-tools.js +90 -0
  14. package/dist/integrations/incidentio/agent-tools.js.map +1 -0
  15. package/dist/integrations/incidentio/claim.d.ts +8 -0
  16. package/dist/integrations/incidentio/claim.d.ts.map +1 -0
  17. package/dist/integrations/incidentio/claim.js +14 -0
  18. package/dist/integrations/incidentio/claim.js.map +1 -0
  19. package/dist/integrations/incidentio/default-rules.d.ts +46 -0
  20. package/dist/integrations/incidentio/default-rules.d.ts.map +1 -0
  21. package/dist/integrations/incidentio/default-rules.js +66 -0
  22. package/dist/integrations/incidentio/default-rules.js.map +1 -0
  23. package/dist/integrations/incidentio/integration.d.ts +48 -2
  24. package/dist/integrations/incidentio/integration.d.ts.map +1 -1
  25. package/dist/integrations/incidentio/integration.js +88 -2
  26. package/dist/integrations/incidentio/integration.js.map +1 -1
  27. package/dist/integrations/incidentio/issue-reconciler.d.ts +2 -0
  28. package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
  29. package/dist/integrations/incidentio/issue-reconciler.js +38 -2
  30. package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
  31. package/dist/integrations/incidentio/routes.d.ts +71 -0
  32. package/dist/integrations/incidentio/routes.d.ts.map +1 -0
  33. package/dist/integrations/incidentio/routes.js +245 -0
  34. package/dist/integrations/incidentio/routes.js.map +1 -0
  35. package/dist/integrations/incidentio/rules.d.ts +55 -0
  36. package/dist/integrations/incidentio/rules.d.ts.map +1 -0
  37. package/dist/integrations/incidentio/rules.js +175 -0
  38. package/dist/integrations/incidentio/rules.js.map +1 -0
  39. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  40. package/dist/integrations/platform/connect/routes.js +10 -4
  41. package/dist/integrations/platform/connect/routes.js.map +1 -1
  42. package/dist/integrations/platform/incidentio/integration.d.ts +61 -4
  43. package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
  44. package/dist/integrations/platform/incidentio/integration.js +371 -22
  45. package/dist/integrations/platform/incidentio/integration.js.map +1 -1
  46. package/dist/routes/oauth.js +2 -5
  47. package/dist/routes/oauth.js.map +1 -1
  48. package/dist/rules/dispatcher.d.ts.map +1 -1
  49. package/dist/rules/dispatcher.js +1 -1
  50. package/dist/rules/dispatcher.js.map +1 -1
  51. package/dist/rules/index.d.ts +2 -2
  52. package/dist/rules/index.d.ts.map +1 -1
  53. package/dist/rules/index.js +2 -2
  54. package/dist/rules/types.d.ts +30 -3
  55. package/dist/rules/types.d.ts.map +1 -1
  56. package/dist/rules/types.js +5 -1
  57. package/dist/rules/types.js.map +1 -1
  58. package/dist/rules/validation.d.ts.map +1 -1
  59. package/dist/rules/validation.js +1 -0
  60. package/dist/rules/validation.js.map +1 -1
  61. package/dist/work-item-branch.d.ts +1 -1
  62. package/dist/work-item-branch.d.ts.map +1 -1
  63. package/dist/work-item-branch.js +3 -2
  64. package/dist/work-item-branch.js.map +1 -1
  65. package/package.json +6 -6
@@ -0,0 +1,175 @@
1
+ import { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from "../../rules/validation.js";
2
+ import { boardForWorkItem, isTerminalWorkItem } from "../../boards/semantics.js";
3
+ import "../../boards/index.js";
4
+ import { incidentioClaimKey } from "./claim.js";
5
+ //#region src/integrations/incidentio/rules.ts
6
+ const RULE_TIMEOUT_MS = 5e3;
7
+ async function withRuleTimeout(promise) {
8
+ let timeout;
9
+ try {
10
+ return await Promise.race([promise, new Promise((_, reject) => {
11
+ timeout = setTimeout(() => reject(/* @__PURE__ */ new Error("FACTORY_RULE_TIMEOUT")), RULE_TIMEOUT_MS);
12
+ })]);
13
+ } finally {
14
+ if (timeout) clearTimeout(timeout);
15
+ }
16
+ }
17
+ var IncidentioRules = class {
18
+ options;
19
+ constructor(options) {
20
+ this.options = options;
21
+ }
22
+ async ingest(input) {
23
+ if (!await this.options.projects.get({
24
+ orgId: input.orgId,
25
+ id: input.factoryProjectId
26
+ })) return {
27
+ status: "missing",
28
+ ingested: 0
29
+ };
30
+ const items = await this.options.storage.list({
31
+ orgId: input.orgId,
32
+ factoryProjectId: input.factoryProjectId
33
+ });
34
+ const itemsBySourceKey = new Map(items.map((item) => [item.externalSource?.externalId, item]));
35
+ const itemsByClaimKey = new Map(items.filter((item) => item.claimKey).map((item) => [item.claimKey, item]));
36
+ const statuses = [];
37
+ for (const issue of input.issues) {
38
+ const relatedItem = itemsByClaimKey.get(incidentioClaimKey(issue.id)) ?? itemsBySourceKey.get(issue.id);
39
+ if (!relatedItem && await this.#heldElsewhere(input, issue)) {
40
+ statuses.push("missing");
41
+ continue;
42
+ }
43
+ statuses.push(await this.#ingestIssue(input, issue, relatedItem));
44
+ }
45
+ if (statuses.some((status) => status === "committed")) return {
46
+ status: "committed",
47
+ ingested: statuses.length
48
+ };
49
+ if (statuses.some((status) => status === "replayed")) return {
50
+ status: "replayed",
51
+ ingested: statuses.length
52
+ };
53
+ return {
54
+ status: "missing",
55
+ ingested: statuses.length
56
+ };
57
+ }
58
+ async #heldElsewhere(input, issue) {
59
+ const heldLive = (row) => row.factoryProjectId !== input.factoryProjectId && !isTerminalWorkItem(this.options.boards, row);
60
+ const claimant = await this.options.storage.getByClaimKey({
61
+ orgId: input.orgId,
62
+ claimKey: incidentioClaimKey(issue.id)
63
+ });
64
+ if (claimant && heldLive(claimant)) return true;
65
+ return (await this.options.storage.listBySource({
66
+ orgId: input.orgId,
67
+ source: {
68
+ integrationId: "incidentio",
69
+ type: "issue",
70
+ externalId: issue.id
71
+ }
72
+ })).some(heldLive);
73
+ }
74
+ async #ingestIssue(input, issue, relatedItem) {
75
+ const ingressId = `incidentio:${issue.id}:${issue.updatedAt}`;
76
+ const actor = {
77
+ type: "human",
78
+ id: input.userId
79
+ };
80
+ const isClosed = issue.stateType === "completed" || issue.stateType === "canceled";
81
+ if (isClosed && !relatedItem) return "missing";
82
+ const event = isClosed ? "followUpClosed" : "followUpObserved";
83
+ const boundBoardId = issue.sourceId ? input.intakeBoards?.[issue.sourceId] : void 0;
84
+ const boundBoard = boundBoardId ? this.options.boards.get(boundBoardId) : void 0;
85
+ const context = {
86
+ tenant: {
87
+ orgId: input.orgId,
88
+ projectId: input.factoryProjectId
89
+ },
90
+ actor,
91
+ ingress: {
92
+ type: "incidentio",
93
+ id: ingressId
94
+ },
95
+ cause: `incidentio.${event}`,
96
+ causalChain: [],
97
+ configVersion: this.options.configVersion,
98
+ ...relatedItem ? {
99
+ item: {
100
+ id: relatedItem.id,
101
+ source: "incidentio-follow-up",
102
+ sourceKey: relatedItem.externalSource?.externalId ?? null,
103
+ parentWorkItemId: relatedItem.parentWorkItemId,
104
+ title: relatedItem.title,
105
+ url: relatedItem.externalSource?.url ?? null,
106
+ stages: relatedItem.stages,
107
+ acceptedAt: relatedItem.acceptedAt,
108
+ metadata: relatedItem.metadata
109
+ },
110
+ board: boardForWorkItem(relatedItem),
111
+ itemRevision: relatedItem.revision
112
+ } : {},
113
+ ...boundBoard ? { intake: {
114
+ board: boundBoard.id,
115
+ initialPhase: boundBoard.initialPhase
116
+ } } : {},
117
+ event,
118
+ issue
119
+ };
120
+ const rule = this.options.incidentioRules[context.event];
121
+ let decision;
122
+ let decisions = [];
123
+ let outcome = { status: "accepted" };
124
+ try {
125
+ decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : void 0;
126
+ if (decision?.type === "reject") outcome = {
127
+ status: "rejected",
128
+ code: decision.code,
129
+ reason: decision.reason
130
+ };
131
+ else if (decision) decisions = validateFactoryRuleDecisions([decision]).map((entry) => {
132
+ assertFactoryDecisionTarget(entry, this.options.boards, relatedItem ? boardForWorkItem(relatedItem) : void 0);
133
+ return { ...entry };
134
+ });
135
+ } catch (error) {
136
+ const timedOut = error instanceof Error && error.message === "FACTORY_RULE_TIMEOUT";
137
+ outcome = {
138
+ status: "rejected",
139
+ code: timedOut ? "timeout" : "rule_error",
140
+ reason: timedOut ? "Factory rule evaluation timed out." : error instanceof Error ? error.message.slice(0, 2e3) : "Factory incident.io rule failed."
141
+ };
142
+ }
143
+ return (await this.options.storage.commitRuleEvaluation({
144
+ orgId: input.orgId,
145
+ factoryProjectId: input.factoryProjectId,
146
+ workItemId: relatedItem?.id ?? null,
147
+ ingress: {
148
+ identity: ingressId,
149
+ triggerType: `incidentio.${event}`
150
+ },
151
+ configVersion: this.options.configVersion,
152
+ expectedRevision: relatedItem?.revision ?? null,
153
+ actor,
154
+ outcome,
155
+ decisions,
156
+ causalChain: [],
157
+ now: /* @__PURE__ */ new Date()
158
+ })).status;
159
+ }
160
+ };
161
+ function attachIncidentioRules(incidentio, context) {
162
+ if (!context.runtime) return void 0;
163
+ const rules = new IncidentioRules({
164
+ projects: context.storage.projects,
165
+ storage: context.runtime.workItems,
166
+ configVersion: context.runtime.configVersion,
167
+ boards: context.runtime.boards,
168
+ incidentioRules: incidentio.rules
169
+ });
170
+ return (input) => rules.ingest(input);
171
+ }
172
+ //#endregion
173
+ export { IncidentioRules, attachIncidentioRules };
174
+
175
+ //# sourceMappingURL=rules.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules.js","names":["#heldElsewhere","#ingestIssue"],"sources":["../../../src/integrations/incidentio/rules.ts"],"sourcesContent":["import { boardForWorkItem, isTerminalWorkItem } from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport type { FactoryIncidentioRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { WorkItemRow, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport { incidentioClaimKey } from './claim.js';\nimport type { IncidentioEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nexport interface IncidentioIssueIngress {\n /** Stable item reference — the prefixed incident.io follow-up id (`incidentio:follow-up:<ulid>`). */\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the follow-up creator, when available. */\n author: string | null;\n /** Reference of the incident this follow-up belongs to, when available. */\n incident: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** incident.io source the follow-up was read from; resolves the bound board via `intakeBoards`. */\n sourceId?: string | null;\n}\n\nexport interface IncidentioRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n boards: BoardRegistry;\n incidentioRules: IncidentioEventRules;\n}\n\nexport interface IncidentioRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: IncidentioIssueIngress[];\n /** Board id per bound incident.io source id, from the project's intake bindings. */\n intakeBoards?: Readonly<Record<string, string>>;\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\nexport class IncidentioRules {\n constructor(private readonly options: IncidentioRulesOptions) {}\n\n async ingest(input: IncidentioRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n\n const items = await this.options.storage.list({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const itemsByClaimKey = new Map(items.filter(item => item.claimKey).map(item => [item.claimKey, item]));\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // The claim finds the card even after a metadata drift; the raw item\n // reference covers cards filed before claims existed.\n const relatedItem = itemsByClaimKey.get(incidentioClaimKey(issue.id)) ?? itemsBySourceKey.get(issue.id);\n // One live card per follow-up per org. The store's claim index is the\n // guarantee; this check spares the dispatcher a refused upsert.\n if (!relatedItem && (await this.#heldElsewhere(input, issue))) {\n statuses.push('missing');\n continue;\n }\n statuses.push(await this.#ingestIssue(input, issue, relatedItem));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #heldElsewhere(input: IncidentioRulesIngress, issue: IncidentioIssueIngress): Promise<boolean> {\n const heldLive = (row: WorkItemRow) =>\n row.factoryProjectId !== input.factoryProjectId && !isTerminalWorkItem(this.options.boards, row);\n const claimant = await this.options.storage.getByClaimKey({\n orgId: input.orgId,\n claimKey: incidentioClaimKey(issue.id),\n });\n if (claimant && heldLive(claimant)) return true;\n // Cards filed before claims existed carry only the item reference.\n const legacy = await this.options.storage.listBySource({\n orgId: input.orgId,\n source: { integrationId: 'incidentio', type: 'issue', externalId: issue.id },\n });\n return legacy.some(heldLive);\n }\n\n async #ingestIssue(\n input: IncidentioRulesIngress,\n issue: IncidentioIssueIngress,\n relatedItem: WorkItemRow | undefined,\n ): Promise<IngressStatus> {\n const ingressId = `incidentio:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed follow-ups without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'followUpClosed' : 'followUpObserved';\n const boundBoardId = issue.sourceId ? input.intakeBoards?.[issue.sourceId] : undefined;\n const boundBoard = boundBoardId ? this.options.boards.get(boundBoardId) : undefined;\n const context: FactoryIncidentioRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'incidentio', id: ingressId },\n cause: `incidentio.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'incidentio-follow-up',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n }\n : {}),\n ...(boundBoard ? { intake: { board: boundBoard.id, initialPhase: boundBoard.initialPhase } } : {}),\n event,\n issue,\n };\n\n const rule = this.options.incidentioRules[context.event];\n let decision: FactoryRuleDecision | void;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.options.boards,\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory incident.io rule failed.',\n };\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId, triggerType: `incidentio.${event}` },\n configVersion: this.options.configVersion,\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n return committed.status;\n }\n}\n\nexport function attachIncidentioRules(\n incidentio: { readonly rules: IncidentioEventRules },\n context: IntegrationContext,\n): ((input: IncidentioRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new IncidentioRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n incidentioRules: incidentio.rules,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;AAUA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF,CAAC,CACH,CAAC;CACH,UAAU;EACR,IAAI,SAAS,aAAa,OAAO;CACnC;AACF;AA0CA,IAAa,kBAAb,MAA6B;CACE;CAA7B,YAAY,SAAkD;EAAjC,KAAA,UAAA;CAAkC;CAE/D,MAAM,OAAO,OAAqF;EAEhG,IAAI,CAAC,MADiB,KAAK,QAAQ,SAAS,IAAI;GAAE,OAAO,MAAM;GAAO,IAAI,MAAM;EAAiB,CAAC,GACpF,OAAO;GAAE,QAAQ;GAAW,UAAU;EAAE;EAEtD,MAAM,QAAQ,MAAM,KAAK,QAAQ,QAAQ,KAAK;GAAE,OAAO,MAAM;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iCAAiC,GAAG,QAAQ,EAAE,CAgFjG"}
@@ -11,10 +11,16 @@ function loose(c) {
11
11
  * for new connect sessions. Provider-specific PRs extend this registry when
12
12
  * their Factory integrations are available.
13
13
  */
14
- const PLATFORM_CONNECT_PROVIDERS = { jira: {
15
- integrationId: "jira",
16
- connectionIntegrationIds: ["jira"]
17
- } };
14
+ const PLATFORM_CONNECT_PROVIDERS = {
15
+ jira: {
16
+ integrationId: "jira",
17
+ connectionIntegrationIds: ["jira"]
18
+ },
19
+ "incident-io": {
20
+ integrationId: "incident-io",
21
+ connectionIntegrationIds: ["incident-io"]
22
+ }
23
+ };
18
24
  async function resolveOrgTenant(c, auth) {
19
25
  if (!auth.enabled()) return { response: c.json({
20
26
  error: "auth_disabled",
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/connect/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` that let the Factory SPA connect and reconnect\n * Platform-managed provider accounts without leaving Factory.\n *\n * The browser cannot talk to the integrations service itself — it has no\n * Platform session — so these routes mint Nango connect/reconnect sessions\n * server-side with the deploy's machine credentials\n * (`MASTRA_PLATFORM_ACCESS_TOKEN`/`MASTRA_PLATFORM_SECRET_KEY`) and hand the\n * short-lived session token back to the SPA, which drives the provider's\n * OAuth popup headlessly via `@nangohq/frontend`. Gating mirrors the\n * Platform's own rule for these providers: a signed-in organization member\n * (org:write parity with Linear), not an organization admin.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport type { RouteAuth } from '../../../routes/route.js';\nimport { PlatformApiClient, PlatformApiError } from '../api-client.js';\n\ntype RouteContext = Context;\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\n\nexport interface PlatformConnectProvider {\n /** Platform integration id used to mint connect sessions. */\n integrationId: string;\n /** Connection `integrationId` variants that belong to this provider. */\n connectionIntegrationIds: readonly string[];\n}\n\n/**\n * Providers the Factory SPA may connect through these routes. Keys are the\n * SPA-facing provider slugs; `integrationId` is the Platform catalog id used\n * for new connect sessions. Provider-specific PRs extend this registry when\n * their Factory integrations are available.\n */\nexport const PLATFORM_CONNECT_PROVIDERS: Record<string, PlatformConnectProvider> = {\n jira: { integrationId: 'jira', connectionIntegrationIds: ['jira'] },\n};\n\ninterface PlatformConnectionRow {\n id: string;\n integrationId: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n displayName?: string | null;\n connectedAt?: string;\n}\n\ninterface PlatformSessionResponse {\n connectionId: string;\n integrationId: string;\n connectUrl: string;\n sessionToken: string;\n expiresAt: string;\n}\n\nexport interface BuildPlatformConnectRoutesOptions {\n auth: RouteAuth;\n client: PlatformApiClient;\n}\n\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n if (!auth.enabled()) {\n return { response: c.json({ error: 'auth_disabled', message: 'Factory auth is not enabled.' }, 403) };\n }\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Provider connections require an organization. Personal accounts cannot connect providers.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\nfunction providerFromParam(c: RouteContext): PlatformConnectProvider | null {\n const provider = c.req.param('provider');\n return provider ? (PLATFORM_CONNECT_PROVIDERS[provider] ?? null) : null;\n}\n\nfunction platformError(c: RouteContext, err: unknown) {\n if (err instanceof PlatformApiError) {\n if (err.status === 409) {\n return c.json({ error: 'session_pending', message: err.message }, 409);\n }\n if (err.status === 403) {\n return c.json({ error: 'platform_forbidden', message: err.message }, 403);\n }\n }\n return c.json({ error: 'platform_request_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the `/web/integrations/platform/*` routes. Callers only mount these\n * when Platform machine credentials are configured.\n */\nexport function buildPlatformConnectRoutes(options: BuildPlatformConnectRoutesOptions): ApiRoute[] {\n const { auth, client } = options;\n\n return [\n registerApiRoute('/web/integrations/platform/:provider/connections', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const result = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connections = result.connections.filter(connection =>\n provider.connectionIntegrationIds.includes(connection.integrationId),\n );\n return c.json({ connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/integrations/${encodeURIComponent(provider.integrationId)}/connect-sessions`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connections/:connectionId/reconnect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n const connectionId = c.req.param('connectionId');\n if (!connectionId) return c.json({ error: 'connection_required' }, 400);\n try {\n // Confirm the connection belongs to this provider before minting so\n // one provider's page cannot reconnect a different provider's\n // connection through this route family.\n const listed = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connection = listed.connections.find(\n candidate =>\n candidate.id === connectionId && provider.connectionIntegrationIds.includes(candidate.integrationId),\n );\n if (!connection) return c.json({ error: 'connection_not_found' }, 404);\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/connections/${encodeURIComponent(connectionId)}/reconnect-session`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n ];\n}\n"],"mappings":";;;;AAwBA,SAAS,MAAM,GAA0B;CACvC,OAAO;AACT;;;;;;;AAeA,MAAa,6BAAsE,EACjF,MAAM;CAAE,eAAe;CAAQ,0BAA0B,CAAC,MAAM;AAAE,EACpE;AAwBA,eAAe,iBACb,GACA,MACiF;CACjF,IAAI,CAAC,KAAK,QAAQ,GAChB,OAAO,EAAE,UAAU,EAAE,KAAK;EAAE,OAAO;EAAiB,SAAS;CAA+B,GAAG,GAAG,EAAE;CAEtG,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;CACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KACV;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF,EACF;CAEF,OAAO,EAAE,QAAQ;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,EAAE;AAClE;AAEA,SAAS,kBAAkB,GAAiD;CAC1E,MAAM,WAAW,EAAE,IAAI,MAAM,UAAU;CACvC,OAAO,WAAY,2BAA2B,aAAa,OAAQ;AACrE;AAEA,SAAS,cAAc,GAAiB,KAAc;CACpD,IAAI,eAAe,kBAAkB;EACnC,IAAI,IAAI,WAAW,KACjB,OAAO,EAAE,KAAK;GAAE,OAAO;GAAmB,SAAS,IAAI;EAAQ,GAAG,GAAG;EAEvE,IAAI,IAAI,WAAW,KACjB,OAAO,EA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AO,EAAE,KAAK,SAAS,GAAG;IAC5B,SAAS,KAAK;KACZ,OAAO,cAAc,GAAG,GAAG;IAC7B;GACF;EACF,CAAC;EACD,iBAAiB,oFAAoF;GACnG,QAAQ;GACR,cAAc;GACd,SAAS,OAAM,eAAc;IAC3B,MAAM,IAAI,MAAM,UAAU;IAC1B,MAAM,WAAW,kBAAkB,CAAC;IACpC,IAAI,CAAC,UAAU,OAAO,EAAE,KAAK,EAAE,OAAO,mBAAmB,GAAG,GAAG;IAC/D,MAAM,WAAW,MAAM,iBAAiB,GAAG,IAAI;IAC/C,IAAI,cAAc,UAAU,OAAO,SAAS;IAC5C,MAAM,eAAe,EAAE,IAAI,MAAM,cAAc;IAC/C,IAAI,CAAC,cAAc,OAAO,EAAE,KAAK,EAAE,OAAO,sBAAsB,GAAG,GAAG;IACtE,IAAI;KASF,IAAI,EAJe,MADE,OAAO,QAAkD,OAAO,iBAAiB,EAAA,CAC5E,YAAY,MACpC,cACE,UAAU,OAAO,gBAAgB,SAAS,yBAAyB,SAAS,UAAU,aAAa,CAEzF,GAAG,OAAO,EAAE,KAAK,EAAE,OAAO,uBAAuB,GAAG,GAAG;KACrE,MAAM,UAAU,MAAM,OAAO,QAC3B,QACA,mBAAmB,mBAAmB,YAAY,EAAE,qBACpD,CAAC,CACH;KACA,EAAE,OAAO,iBAAiB,UAAU;KACpC,OAAO,EAAE,KAAK,SAAS,GAAG;IAC5B,SAAS,KAAK;KACZ,OAAO,cAAc,GAAG,GAAG;IAC7B;GACF;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/connect/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` that let the Factory SPA connect and reconnect\n * Platform-managed provider accounts without leaving Factory.\n *\n * The browser cannot talk to the integrations service itself — it has no\n * Platform session — so these routes mint Nango connect/reconnect sessions\n * server-side with the deploy's machine credentials\n * (`MASTRA_PLATFORM_ACCESS_TOKEN`/`MASTRA_PLATFORM_SECRET_KEY`) and hand the\n * short-lived session token back to the SPA, which drives the provider's\n * OAuth popup headlessly via `@nangohq/frontend`. Gating mirrors the\n * Platform's own rule for these providers: a signed-in organization member\n * (org:write parity with Linear), not an organization admin.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport type { RouteAuth } from '../../../routes/route.js';\nimport { PlatformApiClient, PlatformApiError } from '../api-client.js';\n\ntype RouteContext = Context;\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\n\nexport interface PlatformConnectProvider {\n /** Platform integration id used to mint connect sessions. */\n integrationId: string;\n /** Connection `integrationId` variants that belong to this provider. */\n connectionIntegrationIds: readonly string[];\n}\n\n/**\n * Providers the Factory SPA may connect through these routes. Keys are the\n * SPA-facing provider slugs; `integrationId` is the Platform catalog id used\n * for new connect sessions. Provider-specific PRs extend this registry when\n * their Factory integrations are available.\n */\nexport const PLATFORM_CONNECT_PROVIDERS: Record<string, PlatformConnectProvider> = {\n jira: { integrationId: 'jira', connectionIntegrationIds: ['jira'] },\n 'incident-io': { integrationId: 'incident-io', connectionIntegrationIds: ['incident-io'] },\n};\n\ninterface PlatformConnectionRow {\n id: string;\n integrationId: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n displayName?: string | null;\n connectedAt?: string;\n}\n\ninterface PlatformSessionResponse {\n connectionId: string;\n integrationId: string;\n connectUrl: string;\n sessionToken: string;\n expiresAt: string;\n}\n\nexport interface BuildPlatformConnectRoutesOptions {\n auth: RouteAuth;\n client: PlatformApiClient;\n}\n\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n if (!auth.enabled()) {\n return { response: c.json({ error: 'auth_disabled', message: 'Factory auth is not enabled.' }, 403) };\n }\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Provider connections require an organization. Personal accounts cannot connect providers.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\nfunction providerFromParam(c: RouteContext): PlatformConnectProvider | null {\n const provider = c.req.param('provider');\n return provider ? (PLATFORM_CONNECT_PROVIDERS[provider] ?? null) : null;\n}\n\nfunction platformError(c: RouteContext, err: unknown) {\n if (err instanceof PlatformApiError) {\n if (err.status === 409) {\n return c.json({ error: 'session_pending', message: err.message }, 409);\n }\n if (err.status === 403) {\n return c.json({ error: 'platform_forbidden', message: err.message }, 403);\n }\n }\n return c.json({ error: 'platform_request_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the `/web/integrations/platform/*` routes. Callers only mount these\n * when Platform machine credentials are configured.\n */\nexport function buildPlatformConnectRoutes(options: BuildPlatformConnectRoutesOptions): ApiRoute[] {\n const { auth, client } = options;\n\n return [\n registerApiRoute('/web/integrations/platform/:provider/connections', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const result = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connections = result.connections.filter(connection =>\n provider.connectionIntegrationIds.includes(connection.integrationId),\n );\n return c.json({ connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/integrations/${encodeURIComponent(provider.integrationId)}/connect-sessions`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connections/:connectionId/reconnect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n const connectionId = c.req.param('connectionId');\n if (!connectionId) return c.json({ error: 'connection_required' }, 400);\n try {\n // Confirm the connection belongs to this provider before minting so\n // one provider's page cannot reconnect a different provider's\n // connection through this route family.\n const listed = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connection = listed.connections.find(\n candidate =>\n candidate.id === connectionId && provider.connectionIntegrationIds.includes(candidate.integrationId),\n );\n if (!connection) return c.json({ error: 'connection_not_found' }, 404);\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/connections/${encodeURIComponent(connectionId)}/reconnect-session`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n ];\n}\n"],"mappings":";;;;AAwBA,SAAS,MAAM,GAA0B;CACvC,OAAO;AACT;;;;;;;AAeA,MAAa,6BAAsE;CACjF,MAAM;EAAE,eAAe;EAAQ,0BAA0B,CAAC,MAAM;CAAE;CAClE,eAAe;EAAE,eAAe;EAAe,0BAA0B,CAAC,aAAa;CAAE;AAC3F;AAwBA,eAAe,iBACb,GACA,MACiF;CACjF,IAAI,CAAC,KAAK,QAAQ,GAChB,OAAO,EAAE,UAAU,EAAE,KAAK;EAAE,OAAO;EAAiB,SAAS;CAA+B,GAAG,GAAG,EAAE;CAEtG,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAA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U,aAAa,CAEzF,GAAG,OAAO,EAAE,KAAK,EAAE,OAAO,uBAAuB,GAAG,GAAG;KACrE,MAAM,UAAU,MAAM,OAAO,QAC3B,QACA,mBAAmB,mBAAmB,YAAY,EAAE,qBACpD,CAAC,CACH;KACA,EAAE,OAAO,iBAAiB,UAAU;KACpC,OAAO,EAAE,KAAK,SAAS,GAAG;IAC5B,SAAS,KAAK;KACZ,OAAO,cAAc,GAAG,GAAG;IAC7B;GACF;EACF,CAAC;CACH;AACF"}
@@ -1,17 +1,74 @@
1
+ import type { RequestContext } from '@mastra/core/request-context';
2
+ import type { ApiRoute } from '@mastra/core/server';
1
3
  import type { MastraWorker } from '@mastra/core/worker';
2
- import type { FactoryIntegration, IntegrationContext } from '../../base.js';
4
+ import type { Intake } from '../../../capabilities/intake.js';
5
+ import type { RouteAuth } from '../../../routes/route.js';
6
+ import type { IntakeStorage } from '../../../storage/domains/intake/base.js';
7
+ import type { FactoryProjectsStorage } from '../../../storage/domains/projects/base.js';
8
+ import type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../../base.js';
9
+ import type { IncidentioEventRules, IncidentioRuleOverrides } from '../../incidentio/default-rules.js';
3
10
  import { type PlatformApiClientConfig } from '../api-client.js';
4
11
  export interface PlatformIncidentioIntegrationConfig {
5
12
  clientConfig?: PlatformApiClientConfig;
6
- connectionId?: string;
13
+ /** Per-event replacements for the default Factory incident.io rules. */
14
+ rules?: IncidentioRuleOverrides;
7
15
  }
16
+ interface PlatformIntegrationConnection {
17
+ id: string;
18
+ integrationId: string;
19
+ status: 'active' | 'needs_reauth';
20
+ accountLabel: string | null;
21
+ }
22
+ interface ScopedSourceId {
23
+ connectionId: string;
24
+ sourceId: string;
25
+ }
26
+ export declare function encodeScopedSourceId(connectionId: string, sourceId: string): string;
27
+ export declare function decodeScopedSourceId(value: string): ScopedSourceId | null;
8
28
  export declare class PlatformIncidentioIntegration implements FactoryIntegration {
9
29
  #private;
10
30
  readonly id = "incidentio";
11
- readonly intake: import("../../../capabilities/intake.js").Intake;
12
31
  constructor(config?: PlatformIncidentioIntegrationConfig);
32
+ /** Event rules driving automatic follow-up materialization and close handling. */
33
+ get rules(): IncidentioEventRules;
34
+ initialize({ projects, auth, intake, }: {
35
+ projects: FactoryProjectsStorage;
36
+ auth: RouteAuth;
37
+ intake: IntakeStorage;
38
+ }): void;
39
+ /** Cross-integration intake selection/binding domain — agent-tool authorization. */
40
+ get intakeStorage(): IntakeStorage;
41
+ /** Factory projects domain — maps a session's resourceId to its owning org. */
42
+ get projects(): FactoryProjectsStorage;
43
+ /** Whether the host runs with web auth enabled; every surface is inert without it. */
44
+ get authEnabled(): boolean;
45
+ /**
46
+ * Map a session's resourceId (the factory project id) to its owning org.
47
+ * Same caching semantics as the Jira integration: definitive misses are
48
+ * cached, transient database failures are not.
49
+ */
50
+ resolveOrgId(resourceId: string): Promise<string | null>;
51
+ /**
52
+ * Org-scoped agent tools: the read-only follow-up detail tool for sessions
53
+ * whose resource is a factory project with an active Platform-managed
54
+ * incident.io connection.
55
+ */
56
+ agentTools(args: {
57
+ requestContext: RequestContext;
58
+ }): Promise<IntegrationTools>;
59
+ listConnections(): Promise<PlatformIntegrationConnection[]>;
60
+ hasActiveConnections(): Promise<boolean>;
61
+ clearCaches(): void;
62
+ readonly intake: Intake;
13
63
  workers(ctx: IntegrationContext): MastraWorker[];
14
- routes(): [];
64
+ /**
65
+ * The integration's HTTP surface: `/web/incidentio/*` Mastra `apiRoutes`
66
+ * (status + follow-up listing/detail for Intake), aggregated across every
67
+ * discovered Platform connection. A board-scoped listing also feeds the
68
+ * incident.io event rules.
69
+ */
70
+ routes(ctx: IntegrationContext): ApiRoute[];
15
71
  diagnostics(): Record<string, unknown>;
16
72
  }
73
+ export {};
17
74
  //# sourceMappingURL=integration.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/incidentio/integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE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