@mastra/factory 0.5.0 → 0.6.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/auth.d.ts +2 -0
  3. package/dist/auth.d.ts.map +1 -1
  4. package/dist/auth.js +2 -0
  5. package/dist/auth.js.map +1 -1
  6. package/dist/capabilities/intake.d.ts +1 -0
  7. package/dist/capabilities/intake.d.ts.map +1 -1
  8. package/dist/capabilities/version-control.d.ts +2 -0
  9. package/dist/capabilities/version-control.d.ts.map +1 -1
  10. package/dist/factory.d.ts.map +1 -1
  11. package/dist/factory.js +2 -1
  12. package/dist/factory.js.map +1 -1
  13. package/dist/integrations/base.d.ts +6 -0
  14. package/dist/integrations/base.d.ts.map +1 -1
  15. package/dist/integrations/github/integration.d.ts +1 -0
  16. package/dist/integrations/github/integration.d.ts.map +1 -1
  17. package/dist/integrations/github/integration.js +11 -1
  18. package/dist/integrations/github/integration.js.map +1 -1
  19. package/dist/integrations/github/routes.d.ts.map +1 -1
  20. package/dist/integrations/github/routes.js +20 -46
  21. package/dist/integrations/github/routes.js.map +1 -1
  22. package/dist/integrations/github/rules.d.ts +4 -0
  23. package/dist/integrations/github/rules.d.ts.map +1 -1
  24. package/dist/integrations/github/rules.js +68 -10
  25. package/dist/integrations/github/rules.js.map +1 -1
  26. package/dist/integrations/github/sandbox-release.d.ts +16 -1
  27. package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
  28. package/dist/integrations/github/sandbox-release.js +42 -1
  29. package/dist/integrations/github/sandbox-release.js.map +1 -1
  30. package/dist/integrations/linear/integration.d.ts +2 -0
  31. package/dist/integrations/linear/integration.d.ts.map +1 -1
  32. package/dist/integrations/linear/integration.js +5 -1
  33. package/dist/integrations/linear/integration.js.map +1 -1
  34. package/dist/integrations/linear/routes.d.ts.map +1 -1
  35. package/dist/integrations/linear/routes.js +1 -0
  36. package/dist/integrations/linear/routes.js.map +1 -1
  37. package/dist/integrations/linear/rules.d.ts +2 -0
  38. package/dist/integrations/linear/rules.d.ts.map +1 -1
  39. package/dist/integrations/linear/rules.js.map +1 -1
  40. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  41. package/dist/integrations/platform/github/integration.js +7 -0
  42. package/dist/integrations/platform/github/integration.js.map +1 -1
  43. package/dist/integrations/slack/integration.d.ts.map +1 -1
  44. package/dist/integrations/slack/integration.js +3 -2
  45. package/dist/integrations/slack/integration.js.map +1 -1
  46. package/dist/integrations/slack/slack.d.ts +37 -110
  47. package/dist/integrations/slack/slack.d.ts.map +1 -1
  48. package/dist/integrations/slack/slack.js +49 -44
  49. package/dist/integrations/slack/slack.js.map +1 -1
  50. package/dist/routes/surface.d.ts +11 -1
  51. package/dist/routes/surface.d.ts.map +1 -1
  52. package/dist/routes/surface.js +18 -8
  53. package/dist/routes/surface.js.map +1 -1
  54. package/dist/rules/defaults.d.ts.map +1 -1
  55. package/dist/rules/defaults.js +35 -4
  56. package/dist/rules/defaults.js.map +1 -1
  57. package/dist/rules/start-coordinator.d.ts.map +1 -1
  58. package/dist/rules/start-coordinator.js +7 -26
  59. package/dist/rules/start-coordinator.js.map +1 -1
  60. package/dist/rules/types.d.ts +10 -0
  61. package/dist/rules/types.d.ts.map +1 -1
  62. package/dist/rules/types.js.map +1 -1
  63. package/dist/session/factory-session.d.ts +116 -0
  64. package/dist/session/factory-session.d.ts.map +1 -0
  65. package/dist/session/factory-session.js +162 -0
  66. package/dist/session/factory-session.js.map +1 -0
  67. package/dist/storage/domains/audit/domain.d.ts +9 -2
  68. package/dist/storage/domains/audit/domain.d.ts.map +1 -1
  69. package/dist/storage/domains/audit/domain.js +106 -4
  70. package/dist/storage/domains/audit/domain.js.map +1 -1
  71. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  72. package/dist/storage/domains/work-items/base.js +11 -0
  73. package/dist/storage/domains/work-items/base.js.map +1 -1
  74. package/package.json +7 -7
  75. package/dist/integrations/github/factory-session.d.ts +0 -12
  76. package/dist/integrations/github/factory-session.d.ts.map +0 -1
  77. package/dist/integrations/github/factory-session.js +0 -37
  78. package/dist/integrations/github/factory-session.js.map +0 -1
@@ -1,6 +1,8 @@
1
- import type { ChannelHandler, ChannelHandlers, ResolveResourceId, ResolveThreadId } from '@mastra/core/channels';
1
+ import type { ChannelHandler, ChannelHandlers, ChannelSessionStart, ResolveResourceId, ResolveThreadId } from '@mastra/core/channels';
2
2
  import type { ChannelAccountLink, ChannelAccountLinkKey, ChannelIdentityStorage } from '../../storage/domains/channel-identity/base.js';
3
+ import type { MemorySettingsStorage } from '../../storage/domains/memory-settings/base.js';
3
4
  import type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';
5
+ import type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';
4
6
  import type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';
5
7
  import type { FactoryChannelsConfig } from '../base.js';
6
8
  type HandlerThread = Parameters<ChannelHandler>[0];
@@ -25,14 +27,22 @@ interface SlackChannelDeps {
25
27
  */
26
28
  projects?: FactoryProjectsStorage;
27
29
  /**
28
- * Narrow source-control surface used to make new Slack threads repo-backed:
29
- * when the sender is linked and their factory has a repository, the thread's
30
- * resourceId becomes a Factory user-session id (repo cloned on a
31
- * `slack/{threadTs}` branch) instead of the chat-only `channel:...` id.
32
- * Absent (no source-control integration registered) chat-only sessions as
33
- * before.
30
+ * Storage handle of the integration that owns source control
31
+ * (`IntegrationContext.storage.sourceControlOwner`). Used to make new Slack
32
+ * threads repo-backed: when the sender is linked and their factory has a
33
+ * repository, the thread's resourceId becomes a Factory user-session id (repo
34
+ * cloned on a `slack/{threadTs}` branch) instead of the chat-only
35
+ * `channel:...` id. It also lets a started session read back the project it
36
+ * belongs to. Nothing here is provider-specific — the connection is matched
37
+ * by the handle's own `integrationId`. Absent (no source-control integration
38
+ * registered) → chat-only sessions as before.
34
39
  */
35
- sourceControl?: SlackSourceControl;
40
+ sourceControl?: SourceControlStorageHandle;
41
+ /**
42
+ * Observational-memory settings domain. When provided, a repo-backed session
43
+ * adopts its owner's memory settings on start, matching the web kickoff.
44
+ */
45
+ memorySettings?: MemorySettingsStorage;
36
46
  /**
37
47
  * Factory work-items domain. When provided, a dispatched new-session thread
38
48
  * (DM or mention) upserts a Work-board card in Building (`execute`) carrying
@@ -41,108 +51,6 @@ interface SlackChannelDeps {
41
51
  */
42
52
  workItems?: WorkItemsStorage;
43
53
  }
44
- /**
45
- * The slice of the source-control owner's storage the Slack wiring needs.
46
- * Structural (not the storage types themselves) so slack.ts stays decoupled
47
- * from the owning integration's module graph and tests can stub it.
48
- */
49
- export interface SlackSourceControl {
50
- /**
51
- * Resolve the factory's linked repository — first repo on the factory's
52
- * source-control connection, the same single-repo assumption the web kickoff
53
- * makes.
54
- */
55
- resolveProjectRepository(args: {
56
- orgId: string;
57
- factoryProjectId: string;
58
- }): Promise<{
59
- projectRepositoryId: string;
60
- baseBranch: string;
61
- } | null>;
62
- /** Look up an existing user session for a repo branch (idempotent reuse). */
63
- getSessionForBranch(args: {
64
- projectRepositoryId: string;
65
- userId: string;
66
- branch: string;
67
- }): Promise<{
68
- sessionId: string;
69
- } | null>;
70
- /** Create the durable user-session row the workspace factory materializes. */
71
- createSession(args: {
72
- projectRepositoryId: string;
73
- orgId: string;
74
- userId: string;
75
- branch: string;
76
- baseBranch: string;
77
- }): Promise<{
78
- sessionId: string;
79
- }>;
80
- }
81
- /**
82
- * Structural slice of the source-control owner's storage handle
83
- * (`IntegrationContext.storage.sourceControlOwner`, a `SourceControlStorageHandle`)
84
- * the adapter reads. Structural so slack.ts stays decoupled from the storage
85
- * module graph and tests can stub it. The handle is bound during
86
- * `factory.prepare()`; all access here is lazy (request time).
87
- */
88
- interface SourceControlOwnerSlice {
89
- integrationId: string;
90
- connections: {
91
- list(args: {
92
- orgId: string;
93
- factoryProjectId: string;
94
- }): Promise<Array<{
95
- id: string;
96
- integrationId: string;
97
- }>>;
98
- };
99
- projectRepositories: {
100
- list(args: {
101
- orgId: string;
102
- connectionId: string;
103
- }): Promise<Array<{
104
- id: string;
105
- repositoryId: string;
106
- branch?: string | null;
107
- }>>;
108
- };
109
- repositories: {
110
- get(args: {
111
- orgId: string;
112
- id: string;
113
- }): Promise<{
114
- defaultBranch: string;
115
- } | null>;
116
- };
117
- sessions: {
118
- getForBranch(args: {
119
- projectRepositoryId: string;
120
- userId: string;
121
- branch: string;
122
- }): Promise<{
123
- sessionId: string;
124
- } | null>;
125
- create(input: {
126
- sessionId: string;
127
- projectRepositoryId: string;
128
- orgId: string;
129
- userId: string;
130
- branch: string;
131
- baseBranch: string;
132
- }): Promise<{
133
- sessionId: string;
134
- }>;
135
- };
136
- }
137
- /**
138
- * Adapt the source-control owner's storage handle into the
139
- * {@link SlackSourceControl} surface. Nothing here is GitHub-specific — the
140
- * owner is whichever integration owns source control, matched by its own
141
- * `integrationId`. Repo resolution mirrors the factory's own
142
- * `ensureFactoryRuleSession`: the owner's connection on the factory → its
143
- * first linked repository → pinned branch or repo default as the base.
144
- */
145
- export declare function adaptSourceControlOwner(owner: SourceControlOwnerSlice): SlackSourceControl;
146
54
  /** Outcome of the sender-link gate for one inbound message. */
147
55
  type LinkedSenderResult =
148
56
  /** Gating not configured — dispatch as before account linking existed. */
@@ -226,6 +134,25 @@ export declare function createChannelResourceIdResolver(deps: SlackChannelDeps):
226
134
  * resourceId is a memory key, not a unique thread id.
227
135
  */
228
136
  export declare const resolveChannelThreadId: ResolveThreadId;
137
+ /**
138
+ * Apply the factory's configuration to a Slack-created session the first time
139
+ * its thread reaches the controller.
140
+ *
141
+ * Without this a Slack session runs on the SDK's built-in mode default
142
+ * (`openai/gpt-5.5`), so a factory configured for any other provider fails every
143
+ * message with a missing-credentials error. The web kickoff has always applied
144
+ * the factory default; this brings Slack to the same footing.
145
+ *
146
+ * Only repo-backed threads are configured. Their resourceId IS the Factory
147
+ * session id, which the source-control rows turn back into a project — a
148
+ * chat-only `channel:...` id names no project, so there is nothing to read.
149
+ *
150
+ * Skips a session whose mode already has a model persisted on the thread. That
151
+ * is the durable record of a deliberate choice — either an earlier start or a
152
+ * user's own switch — and re-applying the factory default over it would undo
153
+ * the user's selection every time the process restarts.
154
+ */
155
+ export declare function createChannelSessionStartHook(deps: SlackChannelDeps): ChannelSessionStart;
229
156
  /**
230
157
  * Upsert the Work-board card for a dispatched Slack-thread run. Keyed on the
231
158
  * thread via `externalSource` — the work-items domain's unique
@@ -1 +1 @@
1
- {"version":3,"file":"slack.d.ts","sourceRoot":"","sources":["../../../src/integrations/slack/slack.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,cAAc,EAEd,eAAe,EACf,iBAAiB,EACjB,eAAe,EAChB,MAAM,uBAAuB,CAAC;AAK/B,OAAO,KAAK,EACV,kBAAkB,EAClB,qBAAqB,EACrB,sBAAsB,EACvB,MAAM,gDAAgD,CAAC;AACxD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AACjF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAOxD,KAAK,aAAa,GAAG,UAAU,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC;AACnD,KAAK,cAAc,GAAG,UAAU,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC;AAEpD,uFAAuF;AACvF,UAAU,gBAAgB;IACxB;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,sBAAsB,CAAC;IAClC;;;;;;;OAOG;IACH,aAAa,CAAC,EAAE,kBAAkB,CAAC;IACnC;;;;;OAKG;IACH,SAAS,CAAC,EAAE,gBAAgB,CAAC;CAC9B;AAED;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,wBAAwB,CAAC,IAAI,EAAE;QAC7B,KAA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AC;AAEF,kFAAkF;AAClF,UAAU,gBAAgB;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,gBAAgB,GAAG;IAAE,KAAK,EAAE,gBAAgB,CAAA;CAAE,GAAG,qBAAqB,CAiBrH"}
@@ -1,46 +1,9 @@
1
+ import { hydrateFactorySession, resolveFactoryDefaultModelId, resolveFactoryProjectForSession, resolveFactorySourceRepository } from "../../session/factory-session.js";
1
2
  import { randomUUID } from "crypto";
2
3
  import { createSlackAdapter } from "@mastra/slack";
3
4
  import { Actions, Card, CardText, LinkButton } from "chat";
4
5
  //#region src/integrations/slack/slack.ts
5
6
  /**
6
- * Adapt the source-control owner's storage handle into the
7
- * {@link SlackSourceControl} surface. Nothing here is GitHub-specific — the
8
- * owner is whichever integration owns source control, matched by its own
9
- * `integrationId`. Repo resolution mirrors the factory's own
10
- * `ensureFactoryRuleSession`: the owner's connection on the factory → its
11
- * first linked repository → pinned branch or repo default as the base.
12
- */
13
- function adaptSourceControlOwner(owner) {
14
- return {
15
- async resolveProjectRepository({ orgId, factoryProjectId }) {
16
- const connection = (await owner.connections.list({
17
- orgId,
18
- factoryProjectId
19
- })).find((candidate) => candidate.integrationId === owner.integrationId);
20
- if (!connection) return null;
21
- const first = (await owner.projectRepositories.list({
22
- orgId,
23
- connectionId: connection.id
24
- }))[0];
25
- if (!first) return null;
26
- const repository = await owner.repositories.get({
27
- orgId,
28
- id: first.repositoryId
29
- });
30
- if (!repository) return null;
31
- return {
32
- projectRepositoryId: first.id,
33
- baseBranch: first.branch ?? repository.defaultBranch
34
- };
35
- },
36
- getSessionForBranch: (args) => owner.sessions.getForBranch(args),
37
- createSession: (args) => owner.sessions.create({
38
- sessionId: randomUUID(),
39
- ...args
40
- })
41
- };
42
- }
43
- /**
44
7
  * Read the Slack team id off a raw platform payload (Events API envelope or
45
8
  * slash-command body — both carry `team_id`), duck-typed to build the
46
9
  * workspace-scoped account-link key.
@@ -204,19 +167,21 @@ function createChannelResourceIdResolver(deps) {
204
167
  if (factories.length === 1) factoryProjectId = factories[0].id;
205
168
  }
206
169
  if (!factoryProjectId) return chatOnlyResourceId;
207
- const repo = await sourceControl.resolveProjectRepository({
170
+ const repo = await resolveFactorySourceRepository({
171
+ sourceControl,
208
172
  orgId,
209
173
  factoryProjectId
210
174
  });
211
- if (!repo) return chatOnlyResourceId;
175
+ if (!repo.found) return chatOnlyResourceId;
212
176
  const branch = threadBranch(thread.id);
213
- const existing = await sourceControl.getSessionForBranch({
177
+ const existing = await sourceControl.sessions.getForBranch({
214
178
  projectRepositoryId: repo.projectRepositoryId,
215
179
  userId: link.userId,
216
180
  branch
217
181
  });
218
182
  if (existing) return existing.sessionId;
219
- return (await sourceControl.createSession({
183
+ return (await sourceControl.sessions.create({
184
+ sessionId: randomUUID(),
220
185
  projectRepositoryId: repo.projectRepositoryId,
221
186
  orgId,
222
187
  userId: link.userId,
@@ -240,6 +205,45 @@ function createChannelResourceIdResolver(deps) {
240
205
  */
241
206
  const resolveChannelThreadId = ({ resourceId, defaultThreadId }) => resourceId.startsWith("channel:") ? defaultThreadId : resourceId;
242
207
  /**
208
+ * Apply the factory's configuration to a Slack-created session the first time
209
+ * its thread reaches the controller.
210
+ *
211
+ * Without this a Slack session runs on the SDK's built-in mode default
212
+ * (`openai/gpt-5.5`), so a factory configured for any other provider fails every
213
+ * message with a missing-credentials error. The web kickoff has always applied
214
+ * the factory default; this brings Slack to the same footing.
215
+ *
216
+ * Only repo-backed threads are configured. Their resourceId IS the Factory
217
+ * session id, which the source-control rows turn back into a project — a
218
+ * chat-only `channel:...` id names no project, so there is nothing to read.
219
+ *
220
+ * Skips a session whose mode already has a model persisted on the thread. That
221
+ * is the durable record of a deliberate choice — either an earlier start or a
222
+ * user's own switch — and re-applying the factory default over it would undo
223
+ * the user's selection every time the process restarts.
224
+ */
225
+ function createChannelSessionStartHook(deps) {
226
+ const { projects, sourceControl, memorySettings } = deps;
227
+ return async ({ session, thread }) => {
228
+ if (!projects || !sourceControl) return;
229
+ if (thread.resourceId.startsWith("channel:")) return;
230
+ const modeModelKey = `modeModelId_${session.mode.get()}`;
231
+ if (await session.thread.getSetting({ key: modeModelKey })) return;
232
+ const owner = await resolveFactoryProjectForSession({
233
+ sourceControl,
234
+ sessionId: thread.resourceId
235
+ });
236
+ if (!owner) return;
237
+ const defaultModelId = await resolveFactoryDefaultModelId(projects, owner.factoryProjectId);
238
+ await hydrateFactorySession(session, {
239
+ orgId: owner.orgId,
240
+ userId: owner.userId,
241
+ defaultModelId,
242
+ memorySettings
243
+ });
244
+ };
245
+ }
246
+ /**
243
247
  * The internal Mastra thread the framework created for a channel conversation.
244
248
  * The handler's `thread.id` is the platform thread id (e.g. `slack:C123:ts`),
245
249
  * NOT the internal UUID — the mapping lives in the stored thread's channel
@@ -397,10 +401,11 @@ function createSlackChannelsConfig(deps) {
397
401
  } },
398
402
  handlers: createHandlers(deps),
399
403
  resolveResourceId: createChannelResourceIdResolver(deps),
400
- resolveThreadId: resolveChannelThreadId
404
+ resolveThreadId: resolveChannelThreadId,
405
+ onSessionStart: createChannelSessionStartHook(deps)
401
406
  };
402
407
  }
403
408
  //#endregion
404
- export { adaptSourceControlOwner, createChannelResourceIdResolver, createHandlers, createSlackChannelsConfig, resolveChannelThreadId, resolveFactoryForLink, resolveLinkedSender, upsertThreadWorkItem };
409
+ export { createChannelResourceIdResolver, createChannelSessionStartHook, createHandlers, createSlackChannelsConfig, resolveChannelThreadId, resolveFactoryForLink, resolveLinkedSender, upsertThreadWorkItem };
405
410
 
406
411
  //# sourceMappingURL=slack.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"slack.js","names":[],"sources":["../../../src/integrations/slack/slack.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type {\n ChannelHandler,\n ChannelHandlerContext,\n ChannelHandlers,\n ResolveResourceId,\n ResolveThreadId,\n} from '@mastra/core/channels';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { createSlackAdapter } from '@mastra/slack';\nimport { Card, CardText, Actions, LinkButton } from 'chat';\n\nimport type {\n ChannelAccountLink,\n ChannelAccountLinkKey,\n ChannelIdentityStorage,\n} from '../../storage/domains/channel-identity/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { FactoryChannelsConfig } from '../base.js';\n\n// Derive the thread/message types from the core handler signature rather than\n// importing them from `chat` directly: mc-web can resolve a different `chat`\n// version than @mastra/core, and the two `Thread`/`Message` declarations are\n// structurally incompatible (private fields). Using the handler's own types\n// keeps everything on one version.\ntype HandlerThread = Parameters<ChannelHandler>[0];\ntype HandlerMessage = Parameters<ChannelHandler>[1];\n\n/** Dependencies the Slack channel handlers close over, injected from the web entry. */\ninterface SlackChannelDeps {\n /**\n * The factory's reverse-index store mapping a Slack sender to a Mastra\n * tenant. When provided, inbound messages from an unlinked sender are not\n * dispatched — the run only proceeds (with the sender's tenant stamped on\n * the request context) once they've linked their account. Unlinked senders\n * get an ephemeral \"connect your account\" card instead.\n */\n accountLinks?: ChannelIdentityStorage;\n /**\n * Factory projects domain. When provided (alongside `accountLinks`), a\n * linked sender's run must also resolve to a Factory project before it\n * dispatches: their link's default factory, else their tenant's only\n * factory (stamped back onto the link), else an ephemeral \"pick a default\n * factory\" card and no run. Unset → no factory routing (runs dispatch as\n * before).\n */\n projects?: FactoryProjectsStorage;\n /**\n * Narrow source-control surface used to make new Slack threads repo-backed:\n * when the sender is linked and their factory has a repository, the thread's\n * resourceId becomes a Factory user-session id (repo cloned on a\n * `slack/{threadTs}` branch) instead of the chat-only `channel:...` id.\n * Absent (no source-control integration registered) → chat-only sessions as\n * before.\n */\n sourceControl?: SlackSourceControl;\n /**\n * Factory work-items domain. When provided, a dispatched new-session thread\n * (DM or mention) upserts a Work-board card in Building (`execute`) carrying\n * the Slack thread as its external source and binding the repo-backed\n * session. Best-effort — a failure never blocks the run. Unset → no card.\n */\n workItems?: WorkItemsStorage;\n}\n\n/**\n * The slice of the source-control owner's storage the Slack wiring needs.\n * Structural (not the storage types themselves) so slack.ts stays decoupled\n * from the owning integration's module graph and tests can stub it.\n */\nexport interface SlackSourceControl {\n /**\n * Resolve the factory's linked repository — first repo on the factory's\n * source-control connection, the same single-repo assumption the web kickoff\n * makes.\n */\n resolveProjectRepository(args: {\n orgId: string;\n factoryProjectId: string;\n }): Promise<{ projectRepositoryId: string; baseBranch: string } | null>;\n /** Look up an existing user session for a repo branch (idempotent reuse). */\n getSessionForBranch(args: {\n projectRepositoryId: string;\n userId: string;\n branch: string;\n }): Promise<{ sessionId: string } | null>;\n /** Create the durable user-session row the workspace factory materializes. */\n createSession(args: {\n projectRepositoryId: string;\n orgId: string;\n userId: string;\n branch: string;\n baseBranch: string;\n }): Promise<{ sessionId: string }>;\n}\n\n/**\n * Structural slice of the source-control owner's storage handle\n * (`IntegrationContext.storage.sourceControlOwner`, a `SourceControlStorageHandle`)\n * the adapter reads. Structural so slack.ts stays decoupled from the storage\n * module graph and tests can stub it. The handle is bound during\n * `factory.prepare()`; all access here is lazy (request time).\n */\ninterface SourceControlOwnerSlice {\n integrationId: string;\n connections: {\n list(args: { orgId: string; factoryProjectId: string }): Promise<Array<{ id: string; integrationId: string }>>;\n };\n projectRepositories: {\n list(args: {\n orgId: string;\n connectionId: string;\n }): Promise<Array<{ id: string; repositoryId: string; branch?: string | null }>>;\n };\n repositories: {\n get(args: { orgId: string; id: string }): Promise<{ defaultBranch: string } | null>;\n };\n sessions: {\n getForBranch(args: {\n projectRepositoryId: string;\n userId: string;\n branch: string;\n }): Promise<{ sessionId: string } | null>;\n create(input: {\n sessionId: string;\n projectRepositoryId: string;\n orgId: string;\n userId: string;\n branch: string;\n baseBranch: string;\n }): Promise<{ sessionId: string }>;\n };\n}\n\n/**\n * Adapt the source-control owner's storage handle into the\n * {@link SlackSourceControl} surface. Nothing here is GitHub-specific — the\n * owner is whichever integration owns source control, matched by its own\n * `integrationId`. Repo resolution mirrors the factory's own\n * `ensureFactoryRuleSession`: the owner's connection on the factory → its\n * first linked repository → pinned branch or repo default as the base.\n */\nexport function adaptSourceControlOwner(owner: SourceControlOwnerSlice): SlackSourceControl {\n return {\n async resolveProjectRepository({ orgId, factoryProjectId }) {\n const connections = await owner.connections.list({ orgId, factoryProjectId });\n const connection = connections.find(candidate => candidate.integrationId === owner.integrationId);\n if (!connection) return null;\n const projectRepositories = await owner.projectRepositories.list({ orgId, connectionId: connection.id });\n const first = projectRepositories[0];\n if (!first) return null;\n const repository = await owner.repositories.get({ orgId, id: first.repositoryId });\n if (!repository) return null;\n return { projectRepositoryId: first.id, baseBranch: first.branch ?? repository.defaultBranch };\n },\n getSessionForBranch: args => owner.sessions.getForBranch(args),\n createSession: args => owner.sessions.create({ sessionId: randomUUID(), ...args }),\n };\n}\n\n/**\n * Read the Slack team id off a raw platform payload (Events API envelope or\n * slash-command body — both carry `team_id`), duck-typed to build the\n * workspace-scoped account-link key.\n */\nfunction rawTeamId(rawPayload: unknown): string | undefined {\n if (!rawPayload || typeof rawPayload !== 'object') return undefined;\n const raw = rawPayload as { team_id?: unknown; team?: unknown };\n if (typeof raw.team_id === 'string' && raw.team_id) return raw.team_id;\n if (typeof raw.team === 'string' && raw.team) return raw.team;\n if (raw.team && typeof raw.team === 'object') {\n const id = (raw.team as { id?: unknown }).id;\n if (typeof id === 'string' && id) return id;\n }\n return undefined;\n}\n\n/**\n * The Slack team id survives onto a normalized chat Message only on\n * `message.raw` (the Slack Events API envelope).\n */\nfunction slackTeamId(message: HandlerMessage): string | undefined {\n return rawTeamId(message.raw);\n}\n\n/**\n * Resolve the web-UI origin for links humans open in a browser (Connect card,\n * session deep links). Prefers `MASTRACODE_PUBLIC_URL` — the origin auth\n * cookies and OAuth redirect allow-lists are registered against — over the\n * channels tunnel, which only Slack's servers need to reach.\n */\nfunction webPublicUrl(): string | undefined {\n return process.env.MASTRACODE_PUBLIC_URL ?? process.env.MASTRACODE_CHANNELS_PUBLIC_URL;\n}\n\n/** Outcome of the sender-link gate for one inbound message. */\ntype LinkedSenderResult =\n /** Gating not configured — dispatch as before account linking existed. */\n | { status: 'ungated' }\n /** Sender unlinked — Connect card posted (when possible), do not dispatch. */\n | { status: 'blocked' }\n /** Sender linked — their tenant plus the sender key the link lives under. */\n | { status: 'linked'; link: ChannelAccountLink; key: ChannelAccountLinkKey };\n\n/**\n * Resolve the sender's account link, posting an ephemeral \"connect your\n * account\" card (visible only to the sender) linking into the web UI's\n * Slack-connect flow when they're unlinked.\n */\nexport async function resolveLinkedSender({\n thread,\n message,\n accountLinks,\n}: {\n thread: HandlerThread;\n message: HandlerMessage;\n accountLinks?: ChannelIdentityStorage;\n}): Promise<LinkedSenderResult> {\n if (!accountLinks) return { status: 'ungated' };\n const platform = thread.adapter.name;\n const externalUserId = message.author.userId;\n const externalTeamId = slackTeamId(message);\n // Without a team id we can't identify the workspace-scoped link; treat as\n // unlinked so a run never proceeds tenant-less.\n const key = externalTeamId ? { platform, externalTeamId, externalUserId } : undefined;\n const link = key ? await accountLinks.getAccountLink(key) : null;\n if (link && key) return { status: 'linked', link, key };\n\n const publicUrl = webPublicUrl();\n // A public origin is all the card needs. The link carries no identity: the\n // web app authenticates the visitor, then Slack's OIDC flow proves which\n // Slack account they control. Without an origin, still block, just no card.\n if (publicUrl) {\n await thread.postEphemeral(message.author, buildConnectCard(publicUrl), { fallbackToDM: true });\n }\n return { status: 'blocked' };\n}\n\n/**\n * The \"connect your account\" card. The link is deliberately identity-free —\n * `/connect/slack` sends the visitor to Connections, where \"Connect Slack\"\n * runs the OIDC flow and Slack itself asserts the (team, user) pair.\n */\nfunction buildConnectCard(publicUrl: string) {\n return Card({\n title: 'Connect your account',\n children: [\n CardText('Connect your account to use this agent.'),\n Actions([\n LinkButton({\n url: `${publicUrl}/connect/slack`,\n label: 'Connect account',\n }),\n ]),\n ],\n });\n}\n\n/** Outcome of factory routing for one linked sender's inbound message. */\ntype FactoryRouteResult =\n /** Factory routing not configured — dispatch without a factory. */\n | { status: 'ungated' }\n /** No factory resolved — prompt card posted (when possible), do not dispatch. */\n | { status: 'blocked' }\n /** The Factory project this sender's runs route to. */\n | { status: 'resolved'; factoryProjectId: string; slackWorkItemsEnabled: boolean };\n\n/**\n * Decide which Factory project a linked sender's run belongs to:\n *\n * 1. The link's `defaultFactoryProjectId`, when it still exists (a stale id —\n * deleted factory — falls through as if unset).\n * 2. Else, the tenant's only factory, stamped back onto the link so it shows\n * up (and stays editable) in Connected Accounts settings.\n * 3. Else — zero or several factories — an ephemeral \"pick a default factory\"\n * card deep-linking to settings, and the run is blocked.\n */\nexport async function resolveFactoryForLink({\n thread,\n message,\n link,\n key,\n accountLinks,\n projects,\n}: {\n thread: HandlerThread;\n message: HandlerMessage;\n link: ChannelAccountLink;\n key: ChannelAccountLinkKey;\n accountLinks: ChannelIdentityStorage;\n projects?: FactoryProjectsStorage;\n}): Promise<FactoryRouteResult> {\n if (!projects) return { status: 'ungated' };\n // Factories are org-scoped; a personal account (no org) has none and lands\n // on the prompt below.\n const orgId = link.orgId ?? '';\n\n if (link.defaultFactoryProjectId) {\n const existing = await projects.get({ orgId, id: link.defaultFactoryProjectId });\n if (existing) {\n return {\n status: 'resolved',\n factoryProjectId: existing.id,\n slackWorkItemsEnabled: existing.slackWorkItemsEnabled,\n };\n }\n }\n\n const factories = orgId ? await projects.list({ orgId }) : [];\n if (factories.length === 1) {\n const only = factories[0]!;\n await accountLinks.setDefaultFactory({ ...key, userId: link.userId, factoryProjectId: only.id });\n return {\n status: 'resolved',\n factoryProjectId: only.id,\n slackWorkItemsEnabled: only.slackWorkItemsEnabled,\n };\n }\n\n const publicUrl = webPublicUrl();\n if (publicUrl) {\n await thread.postEphemeral(\n message.author,\n Card({\n title: 'Pick a default factory',\n children: [\n CardText(\n factories.length === 0\n ? 'Your account has no factory yet. Create one in the web app, then message me again.'\n : 'Your account has several factories. Pick which one Slack sessions should go to, then message me again.',\n ),\n Actions([\n LinkButton({\n url: `${publicUrl}/settings/connections`,\n label: 'Open settings',\n }),\n ]),\n ],\n }),\n { fallbackToDM: true },\n );\n }\n return { status: 'blocked' };\n}\n\n/**\n * Deterministic per-thread branch name: `slack/{threadTs}` with characters\n * outside the sandbox git-ref allow-list (`[A-Za-z0-9_./-]`, and `.` for\n * readability) mapped to `-`. `thread.id` is `{channelId}:{threadTs}`\n * (platform-prefixed on handler threads) — the trailing segment is the ts.\n */\nfunction threadBranch(threadId: string): string {\n const ts = threadId.split(':').at(-1) ?? threadId;\n return `slack/${ts.replace(/[^A-Za-z0-9_/-]/g, '-')}`;\n}\n\n/**\n * Resolve the resourceId for a NEW Slack channel thread. A linked sender whose\n * factory has a repository gets a Factory user-session id — the controller\n * session then materializes the repo sandbox via the factory's dynamic\n * workspace (clone + PAT), the session shows up in the web Sessions list, and\n * View Session deep-links land on the normal workspace route. Everything else\n * (unlinked, unrouted, repo-less, or no source control) keeps the chat-only\n * `defaultResourceId`.\n *\n * Pure lookups only — cards for unlinked/unrouted senders are the dispatch\n * gate's job; this hook must never post.\n */\nexport function createChannelResourceIdResolver(deps: SlackChannelDeps): ResolveResourceId {\n const { accountLinks, projects, sourceControl } = deps;\n return async ({ platform, thread, message }) => {\n // NOT the hook's `defaultResourceId`: configuring a custom resolver\n // bypasses AgentControllerChannels' own `channel:{thread.id}` derivation\n // (agent-controller-channels.ts `resolveChannelResourceId`), and the base\n // default is the per-USER memory key. Chat-only fallbacks must stay\n // per-thread, so reproduce the controller default here.\n const chatOnlyResourceId = `channel:${thread.id}`;\n if (!accountLinks || !projects || !sourceControl) return chatOnlyResourceId;\n try {\n const externalTeamId = rawTeamId(message.raw);\n if (!externalTeamId) return chatOnlyResourceId;\n const link = await accountLinks.getAccountLink({\n platform,\n externalTeamId,\n externalUserId: message.author.userId,\n });\n if (!link) return chatOnlyResourceId;\n\n // Same chain as `resolveFactoryForLink`, minus prompts/stamping: the\n // dispatch gate has already run (and stamped a lone factory) by the\n // time a new thread is created, so this is a read-only re-resolve.\n const orgId = link.orgId ?? '';\n let factoryProjectId: string | undefined;\n if (link.defaultFactoryProjectId && (await projects.get({ orgId, id: link.defaultFactoryProjectId }))) {\n factoryProjectId = link.defaultFactoryProjectId;\n } else if (orgId) {\n const factories = await projects.list({ orgId });\n if (factories.length === 1) factoryProjectId = factories[0]!.id;\n }\n if (!factoryProjectId) return chatOnlyResourceId;\n\n const repo = await sourceControl.resolveProjectRepository({ orgId, factoryProjectId });\n if (!repo) return chatOnlyResourceId;\n\n const branch = threadBranch(thread.id);\n const existing = await sourceControl.getSessionForBranch({\n projectRepositoryId: repo.projectRepositoryId,\n userId: link.userId,\n branch,\n });\n if (existing) return existing.sessionId;\n const session = await sourceControl.createSession({\n projectRepositoryId: repo.projectRepositoryId,\n orgId,\n userId: link.userId,\n branch,\n baseBranch: repo.baseBranch,\n });\n return session.sessionId;\n } catch (error) {\n // Fall back to a chat-only session rather than dropping the message.\n console.warn('[slack] repo-backed session resolution failed for thread', thread.id, error);\n return chatOnlyResourceId;\n }\n };\n}\n\n/**\n * Thread id for a NEW Slack channel thread. Repo-backed threads take the\n * user-session id AS their thread id, matching the web convention\n * (FactoryStartCoordinator seeds threads with threadId = sessionId) so\n * `/workspaces/{sessionId}/threads/{sessionId}` resolves Slack-created\n * sessions exactly like web-created ones — no `?resourceId=` override needed.\n * Chat-only threads keep the default random id: their `channel:...`\n * resourceId is a memory key, not a unique thread id.\n */\nexport const resolveChannelThreadId: ResolveThreadId = ({ resourceId, defaultThreadId }) =>\n resourceId.startsWith('channel:') ? defaultThreadId : resourceId;\n\n/**\n * The internal Mastra thread the framework created for a channel conversation.\n * The handler's `thread.id` is the platform thread id (e.g. `slack:C123:ts`),\n * NOT the internal UUID — the mapping lives in the stored thread's channel\n * metadata.\n */\nasync function findInternalThread(mastra: Mastra | undefined, thread: HandlerThread) {\n const store = await mastra?.getStorage()?.getStore('memory');\n const { threads } = (await store?.listThreads({\n filter: {\n metadata: {\n channel_platform: thread.adapter.name,\n channel_externalThreadId: thread.id,\n channel_externalChannelId: thread.channelId,\n },\n },\n perPage: 1,\n })) ?? { threads: [] };\n return threads[0];\n}\n\n/**\n * Build the \"new session\" handler for mention / direct-message events. A mention or\n * DM on a not-yet-subscribed thread starts a NEW session; once subscribed, later\n * events are follow-ups and don't re-announce.\n */\n/**\n * Run the account-link + factory-routing gates for one inbound message.\n * Returns `null` when the run must not dispatch (a prompt card was posted\n * where possible); otherwise the dispatch context — with `routed` present\n * only when a linked sender resolved to a factory.\n */\nasync function gateDispatch(\n thread: HandlerThread,\n message: HandlerMessage,\n { accountLinks, projects }: SlackChannelDeps,\n ctx: ChannelHandlerContext,\n): Promise<{\n routed?: { link: ChannelAccountLink; factoryProjectId: string; slackWorkItemsEnabled: boolean };\n} | null> {\n const sender = await resolveLinkedSender({ thread, message, accountLinks });\n if (sender.status === 'blocked') return null;\n // Linked senders must also route to a Factory project before a run starts.\n if (sender.status === 'linked' && accountLinks) {\n // Stamp the tenant on the run's request context — the single seam\n // `resolveCredentialStore` reads to load this sender's model credentials.\n // This belongs to the link, not to the routing: a linked sender whose\n // factory routing comes back `ungated` still exits below and dispatches, so\n // stamping only in the routed branch would silently run them on default\n // credentials.\n ctx.requestContext.set('user', { id: sender.link.userId, organizationId: sender.link.orgId });\n\n const route = await resolveFactoryForLink({ thread, message, ...sender, accountLinks, projects });\n if (route.status === 'blocked') return null;\n if (route.status === 'resolved') {\n return {\n routed: {\n link: sender.link,\n factoryProjectId: route.factoryProjectId,\n slackWorkItemsEnabled: route.slackWorkItemsEnabled,\n },\n };\n }\n }\n return {};\n}\n\n/**\n * Upsert the Work-board card for a dispatched Slack-thread run. Keyed on the\n * thread via `externalSource` — the work-items domain's unique\n * `(factory_project_id, source_key)` index makes repeat messages reuse the\n * same card, and `reuseMode: 'preserve'` keeps a card a human already dragged\n * across stages untouched. The card lands in Building (`execute`) for every\n * dispatched thread (DM or mention) — there is deliberately no per-origin\n * stage split; smart routing is a follow-up.\n *\n * The session id / branch / threadId and the workspace deep-link are resolved\n * by the caller (which already looked up the internal thread), so this helper\n * just shapes and writes. Best-effort: the run is already dispatched, so a\n * failure logs instead of throwing — work-item creation must never abort a Slack run.\n */\nexport async function upsertThreadWorkItem({\n workItems,\n thread,\n message,\n link,\n factoryProjectId,\n session,\n url,\n}: {\n workItems: WorkItemsStorage;\n thread: HandlerThread;\n message: HandlerMessage;\n link: ChannelAccountLink;\n factoryProjectId: string;\n /**\n * The repo-backed Factory session to bind under the `chat` role, or\n * `undefined` for a chat-only thread (no Factory session to bind).\n */\n session?: { sessionId: string; branch: string; threadId: string };\n /** Workspace deep-link to the running session; omitted when no public URL. */\n url?: string;\n}): Promise<void> {\n try {\n const title = message.text.length > 80 ? `${message.text.slice(0, 79)}…` : message.text;\n\n await workItems.upsert({\n orgId: link.orgId ?? '',\n userId: link.userId,\n factoryProjectId,\n reuseMode: 'preserve',\n input: {\n title: title || 'Slack thread',\n // `integrationId` is the platform ('slack'); `type` is a single\n // constant (no DM/mention distinction); `externalId` is the stable\n // platform thread id — together they form the idempotency key.\n externalSource: {\n integrationId: thread.adapter.name,\n type: 'slack-thread',\n externalId: thread.id,\n ...(url ? { url } : {}),\n },\n stages: ['execute'],\n ...(session ? { sessions: { chat: session } } : {}),\n },\n });\n } catch (error) {\n console.warn('[slack] work-item creation failed for thread', thread.id, error);\n }\n}\n\nfunction createNewSessionChatHandler(deps: SlackChannelDeps): ChannelHandler {\n const { workItems } = deps;\n return async (thread, message, defaultHandler, ctx) => {\n // Gate on the sender having linked their Slack account to a Mastra tenant.\n // Unlinked → post the ephemeral Connect card and stop; no session/run is\n // created (which would otherwise be tenant-less and fail credential\n // resolution). This handler is the only gate — core dispatches whatever\n // reaches it — so every slot that can start a run must call it.\n const gate = await gateDispatch(thread, message, deps, ctx);\n if (!gate) return;\n\n // A mention on a not-yet-subscribed thread is a NEW session. The\n // default handler auto-subscribes, so once subscribed this is a\n // follow-up mention — don't re-announce.\n const isNewSession = !(await thread.isSubscribed());\n\n // Run the framework handler first so the internal Mastra thread and\n // controller session are created before we build the deep link.\n await defaultHandler(thread, message);\n\n if (!isNewSession) return;\n\n // The internal-thread lookup and deep-link are needed by BOTH the\n // announcement card AND work-item creation, so they run BEFORE the\n // card-only `MASTRACODE_PUBLIC_URL` gate — a deployment without a public\n // origin should still create board cards, just without a clickable link.\n const internalThread = await findInternalThread(ctx.mastra, thread);\n if (!internalThread) {\n console.warn('[onMention] no internal thread found for', thread.id);\n return;\n }\n\n // When the sender routed to a factory we know exactly which workspace the\n // session belongs to — deep-link straight into it. A repo-backed thread's\n // resourceId IS the Factory user-session id, so the link lands on the same\n // route a web-started run navigates to; chat-only threads keep the literal\n // `channel` segment (the real resource rides the `?resourceId=` override).\n // Unrouted senders fall back to the factory-agnostic /threads/ redirect.\n // One predicate drives both the path segment and the query param, so the\n // two can never disagree about what the URL already carries.\n const isChatOnly = internalThread.resourceId.startsWith('channel:');\n const workspaceSegment = isChatOnly ? 'channel' : encodeURIComponent(internalThread.resourceId);\n const threadPath = gate.routed\n ? `/factories/${encodeURIComponent(gate.routed.factoryProjectId)}/workspaces/${workspaceSegment}/threads/${encodeURIComponent(internalThread.id)}`\n : `/threads/${internalThread.id}`;\n\n // The param is an override for a URL that can't otherwise name its\n // resource. A routed repo-backed thread already spells the resourceId out\n // as its workspace segment, so appending it again is duplication the app\n // ignores. Chat-only threads need it (their segment is the literal string\n // `channel`), and so does the unrouted fallback, which has no workspace\n // segment at all — `ChannelThreadRedirect` forwards the search through.\n //\n // One shared deep-link: the card's button and the work-item `url` read the\n // SAME value so they can never drift. Undefined without a public origin —\n // the card is then skipped, but the work item is still created (url omitted).\n const needsResourceParam = isChatOnly || !gate.routed;\n const deepLink = process.env.MASTRACODE_PUBLIC_URL\n ? needsResourceParam\n ? `${process.env.MASTRACODE_PUBLIC_URL}${threadPath}?resourceId=${encodeURIComponent(internalThread.resourceId)}`\n : `${process.env.MASTRACODE_PUBLIC_URL}${threadPath}`\n : undefined;\n\n // A dispatched, routed new-session thread becomes a Work-board card in\n // Building. Only routed senders (linked → factory) have the org/user/factory\n // a work item needs. Bind the repo-backed Factory session under the `chat`\n // role; a chat-only `channel:` resourceId is NOT a session id, so bind\n // nothing rather than a bad id. Best-effort (the helper swallows failures).\n if (workItems && gate.routed?.slackWorkItemsEnabled) {\n const session = isChatOnly\n ? undefined\n : { sessionId: internalThread.resourceId, branch: threadBranch(thread.id), threadId: internalThread.id };\n await upsertThreadWorkItem({\n workItems,\n thread,\n message,\n link: gate.routed.link,\n factoryProjectId: gate.routed.factoryProjectId,\n session,\n url: deepLink,\n });\n }\n\n // The announcement card is only useful with a public origin to deep-link\n // to — otherwise the link would be `undefined/threads/...`. Without one the\n // session (and now the work item) still exist; we just skip the broken card.\n if (!deepLink) return;\n\n await thread.post(\n Card({\n title: 'New session started',\n children: [Actions([LinkButton({ url: deepLink, label: 'View session' })])],\n }),\n );\n };\n}\nexport const createHandlers = (deps: SlackChannelDeps): ChannelHandlers => {\n const newSessionChatHandler = createNewSessionChatHandler(deps);\n\n return {\n onSubscribedMessage: async (thread, message, defaultHandler, ctx) => {\n // `aside` as its own leading word lets humans talk in a subscribed\n // thread without the bot replying. Word boundary so messages that\n // merely start with \"aside...\" (e.g. \"asides can wait\") still route.\n if (/^aside\\b/i.test(message.text)) return;\n // A subscribed follow-up from an unlinked sender must not run either\n // (e.g. the link was removed mid-conversation), and it must still\n // resolve a factory (e.g. the default was cleared or its factory\n // deleted mid-conversation).\n const gate = await gateDispatch(thread, message, deps, ctx);\n if (!gate) return;\n await defaultHandler(thread, message);\n },\n onMention: newSessionChatHandler,\n onDirectMessage: newSessionChatHandler,\n };\n};\n\n/** Slack app credentials, passed in explicitly rather than read from env here. */\ninterface SlackCredentials {\n clientId?: string;\n clientSecret?: string;\n signingSecret: string;\n botToken?: string;\n}\n\nexport function createSlackChannelsConfig(deps: SlackChannelDeps & { slack: SlackCredentials }): FactoryChannelsConfig {\n return {\n adapters: {\n slack: {\n adapter: createSlackAdapter(deps.slack),\n toolDisplay: 'hidden',\n },\n },\n handlers: createHandlers(deps),\n // New linked+repo-backed threads own a Factory user-session id as their\n // resourceId, which is what makes the controller session repo-backed.\n resolveResourceId: createChannelResourceIdResolver(deps),\n resolveThreadId: resolveChannelThreadId,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAgJA,SAAgB,wBAAwB,OAAoD;CAC1F,OAAO;EACL,MAAM,yBAAyB,EAAE,OAAO,oBAAoB;GAE1D,MAAM,cAAa,MADO,MAAM,YAAY,KAAK;IAAE;IAAO;GAAiB,CAAC,EAAA,CAC7C,MAAK,cAAa,UAAU,kBAAkB,MAAM,aAAa;GAChG,IAAI,CAAC,YAAY,OAAO;GAExB,MAAM,SAAQ,MADoB,MAAM,oBAAoB,KAAK;IAAE;IAAO,cAAc,WAAW;GAAG,CAAC,EAAA,CACrE;GAClC,IAAI,CAAC,OAAO,OAAO;GACnB,MAAM,aAAa,MAAM,MAAM,aAAa,IAAI;IAAE;IAAO,IAAI,MAAM;GAAa,CAAC;GACjF,IAAI,CAAC,YAAY,OAAO;GACxB,OAAO;IAAE,qBAAqB,MAAM;IAAI,YAAY,MAAM,UAAU,WAAW;GAAc;EAC/F;EACA,sBAAqB,SAAQ,MAAM,SAAS,aAAa,IAAI;EAC7D,gBAAe,SAAQ,MAAM,SAAS,OAAO;GAAE,WAAW,WAAW;GAAG,GAAG;EAAK,CAAC;CACnF;AACF;;;;;;AAOA,SAAS,UAAU,YAAyC;CAC1D,IAAI,CAAC,cAAc,OAAO,eAAe,UAAU,OAAO,KAAA;CAC1D,MAAM,MAAM;CACZ,IAAI,OAAO,IAAI,YAAY,YAAY,IAAI,SAAS,OAAO,IAAI;CAC/D,IAAI,OAAO,IAAI,SAAS,YAAY,IAAI,MAAM,OAAO,IAAI;CACzD,IAAI,IAAI,QAAQ,OAAO,IAAI,S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CACzE,MAAM,wBAAwB,4BAA4B,IAAI;CAE9D,OAAO;EACL,qBAAqB,OAAO,QAAQ,SAAS,gBAAgB,QAAQ;GAInE,IAAI,YAAY,KAAK,QAAQ,IAAI,GAAG;GAMpC,IAAI,CAAC,MADc,aAAa,QAAQ,SAAS,MAAM,GAAG,GAC/C;GACX,MAAM,eAAe,QAAQ,OAAO;EACtC;EACA,WAAW;EACX,iBAAiB;CACnB;AACF;AAUA,SAAgB,0BAA0B,MAA6E;CACrH,OAAO;EACL,UAAU,EACR,OAAO;GACL,SAAS,mBAAmB,KAAK,KAAK;GACtC,aAAa;EACf,EACF;EACA,UAAU,eAAe,IAAI;EAG7B,mBAAmB,gCAAgC,IAAI;EACvD,iBAAiB;CACnB;AACF"}
1
+ {"version":3,"file":"slack.js","names":[],"sources":["../../../src/integrations/slack/slack.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type {\n ChannelHandler,\n ChannelHandlerContext,\n ChannelHandlers,\n ChannelSessionStart,\n ResolveResourceId,\n ResolveThreadId,\n} from '@mastra/core/channels';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { createSlackAdapter } from '@mastra/slack';\nimport { Card, CardText, Actions, LinkButton } from 'chat';\n\nimport {\n hydrateFactorySession,\n resolveFactoryDefaultModelId,\n resolveFactoryProjectForSession,\n resolveFactorySourceRepository,\n} from '../../session/factory-session.js';\nimport type {\n ChannelAccountLink,\n ChannelAccountLinkKey,\n ChannelIdentityStorage,\n} from '../../storage/domains/channel-identity/base.js';\nimport type { MemorySettingsStorage } from '../../storage/domains/memory-settings/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { FactoryChannelsConfig } from '../base.js';\n\n// Derive the thread/message types from the core handler signature rather than\n// importing them from `chat` directly: mc-web can resolve a different `chat`\n// version than @mastra/core, and the two `Thread`/`Message` declarations are\n// structurally incompatible (private fields). Using the handler's own types\n// keeps everything on one version.\ntype HandlerThread = Parameters<ChannelHandler>[0];\ntype HandlerMessage = Parameters<ChannelHandler>[1];\n\n/** Dependencies the Slack channel handlers close over, injected from the web entry. */\ninterface SlackChannelDeps {\n /**\n * The factory's reverse-index store mapping a Slack sender to a Mastra\n * tenant. When provided, inbound messages from an unlinked sender are not\n * dispatched — the run only proceeds (with the sender's tenant stamped on\n * the request context) once they've linked their account. Unlinked senders\n * get an ephemeral \"connect your account\" card instead.\n */\n accountLinks?: ChannelIdentityStorage;\n /**\n * Factory projects domain. When provided (alongside `accountLinks`), a\n * linked sender's run must also resolve to a Factory project before it\n * dispatches: their link's default factory, else their tenant's only\n * factory (stamped back onto the link), else an ephemeral \"pick a default\n * factory\" card and no run. Unset → no factory routing (runs dispatch as\n * before).\n */\n projects?: FactoryProjectsStorage;\n /**\n * Storage handle of the integration that owns source control\n * (`IntegrationContext.storage.sourceControlOwner`). Used to make new Slack\n * threads repo-backed: when the sender is linked and their factory has a\n * repository, the thread's resourceId becomes a Factory user-session id (repo\n * cloned on a `slack/{threadTs}` branch) instead of the chat-only\n * `channel:...` id. It also lets a started session read back the project it\n * belongs to. Nothing here is provider-specific — the connection is matched\n * by the handle's own `integrationId`. Absent (no source-control integration\n * registered) → chat-only sessions as before.\n */\n sourceControl?: SourceControlStorageHandle;\n /**\n * Observational-memory settings domain. When provided, a repo-backed session\n * adopts its owner's memory settings on start, matching the web kickoff.\n */\n memorySettings?: MemorySettingsStorage;\n /**\n * Factory work-items domain. When provided, a dispatched new-session thread\n * (DM or mention) upserts a Work-board card in Building (`execute`) carrying\n * the Slack thread as its external source and binding the repo-backed\n * session. Best-effort — a failure never blocks the run. Unset → no card.\n */\n workItems?: WorkItemsStorage;\n}\n\n/**\n * Read the Slack team id off a raw platform payload (Events API envelope or\n * slash-command body — both carry `team_id`), duck-typed to build the\n * workspace-scoped account-link key.\n */\nfunction rawTeamId(rawPayload: unknown): string | undefined {\n if (!rawPayload || typeof rawPayload !== 'object') return undefined;\n const raw = rawPayload as { team_id?: unknown; team?: unknown };\n if (typeof raw.team_id === 'string' && raw.team_id) return raw.team_id;\n if (typeof raw.team === 'string' && raw.team) return raw.team;\n if (raw.team && typeof raw.team === 'object') {\n const id = (raw.team as { id?: unknown }).id;\n if (typeof id === 'string' && id) return id;\n }\n return undefined;\n}\n\n/**\n * The Slack team id survives onto a normalized chat Message only on\n * `message.raw` (the Slack Events API envelope).\n */\nfunction slackTeamId(message: HandlerMessage): string | undefined {\n return rawTeamId(message.raw);\n}\n\n/**\n * Resolve the web-UI origin for links humans open in a browser (Connect card,\n * session deep links). Prefers `MASTRACODE_PUBLIC_URL` — the origin auth\n * cookies and OAuth redirect allow-lists are registered against — over the\n * channels tunnel, which only Slack's servers need to reach.\n */\nfunction webPublicUrl(): string | undefined {\n return process.env.MASTRACODE_PUBLIC_URL ?? process.env.MASTRACODE_CHANNELS_PUBLIC_URL;\n}\n\n/** Outcome of the sender-link gate for one inbound message. */\ntype LinkedSenderResult =\n /** Gating not configured — dispatch as before account linking existed. */\n | { status: 'ungated' }\n /** Sender unlinked — Connect card posted (when possible), do not dispatch. */\n | { status: 'blocked' }\n /** Sender linked — their tenant plus the sender key the link lives under. */\n | { status: 'linked'; link: ChannelAccountLink; key: ChannelAccountLinkKey };\n\n/**\n * Resolve the sender's account link, posting an ephemeral \"connect your\n * account\" card (visible only to the sender) linking into the web UI's\n * Slack-connect flow when they're unlinked.\n */\nexport async function resolveLinkedSender({\n thread,\n message,\n accountLinks,\n}: {\n thread: HandlerThread;\n message: HandlerMessage;\n accountLinks?: ChannelIdentityStorage;\n}): Promise<LinkedSenderResult> {\n if (!accountLinks) return { status: 'ungated' };\n const platform = thread.adapter.name;\n const externalUserId = message.author.userId;\n const externalTeamId = slackTeamId(message);\n // Without a team id we can't identify the workspace-scoped link; treat as\n // unlinked so a run never proceeds tenant-less.\n const key = externalTeamId ? { platform, externalTeamId, externalUserId } : undefined;\n const link = key ? await accountLinks.getAccountLink(key) : null;\n if (link && key) return { status: 'linked', link, key };\n\n const publicUrl = webPublicUrl();\n // A public origin is all the card needs. The link carries no identity: the\n // web app authenticates the visitor, then Slack's OIDC flow proves which\n // Slack account they control. Without an origin, still block, just no card.\n if (publicUrl) {\n await thread.postEphemeral(message.author, buildConnectCard(publicUrl), { fallbackToDM: true });\n }\n return { status: 'blocked' };\n}\n\n/**\n * The \"connect your account\" card. The link is deliberately identity-free —\n * `/connect/slack` sends the visitor to Connections, where \"Connect Slack\"\n * runs the OIDC flow and Slack itself asserts the (team, user) pair.\n */\nfunction buildConnectCard(publicUrl: string) {\n return Card({\n title: 'Connect your account',\n children: [\n CardText('Connect your account to use this agent.'),\n Actions([\n LinkButton({\n url: `${publicUrl}/connect/slack`,\n label: 'Connect account',\n }),\n ]),\n ],\n });\n}\n\n/** Outcome of factory routing for one linked sender's inbound message. */\ntype FactoryRouteResult =\n /** Factory routing not configured — dispatch without a factory. */\n | { status: 'ungated' }\n /** No factory resolved — prompt card posted (when possible), do not dispatch. */\n | { status: 'blocked' }\n /** The Factory project this sender's runs route to. */\n | { status: 'resolved'; factoryProjectId: string; slackWorkItemsEnabled: boolean };\n\n/**\n * Decide which Factory project a linked sender's run belongs to:\n *\n * 1. The link's `defaultFactoryProjectId`, when it still exists (a stale id —\n * deleted factory — falls through as if unset).\n * 2. Else, the tenant's only factory, stamped back onto the link so it shows\n * up (and stays editable) in Connected Accounts settings.\n * 3. Else — zero or several factories — an ephemeral \"pick a default factory\"\n * card deep-linking to settings, and the run is blocked.\n */\nexport async function resolveFactoryForLink({\n thread,\n message,\n link,\n key,\n accountLinks,\n projects,\n}: {\n thread: HandlerThread;\n message: HandlerMessage;\n link: ChannelAccountLink;\n key: ChannelAccountLinkKey;\n accountLinks: ChannelIdentityStorage;\n projects?: FactoryProjectsStorage;\n}): Promise<FactoryRouteResult> {\n if (!projects) return { status: 'ungated' };\n // Factories are org-scoped; a personal account (no org) has none and lands\n // on the prompt below.\n const orgId = link.orgId ?? '';\n\n if (link.defaultFactoryProjectId) {\n const existing = await projects.get({ orgId, id: link.defaultFactoryProjectId });\n if (existing) {\n return {\n status: 'resolved',\n factoryProjectId: existing.id,\n slackWorkItemsEnabled: existing.slackWorkItemsEnabled,\n };\n }\n }\n\n const factories = orgId ? await projects.list({ orgId }) : [];\n if (factories.length === 1) {\n const only = factories[0]!;\n await accountLinks.setDefaultFactory({ ...key, userId: link.userId, factoryProjectId: only.id });\n return {\n status: 'resolved',\n factoryProjectId: only.id,\n slackWorkItemsEnabled: only.slackWorkItemsEnabled,\n };\n }\n\n const publicUrl = webPublicUrl();\n if (publicUrl) {\n await thread.postEphemeral(\n message.author,\n Card({\n title: 'Pick a default factory',\n children: [\n CardText(\n factories.length === 0\n ? 'Your account has no factory yet. Create one in the web app, then message me again.'\n : 'Your account has several factories. Pick which one Slack sessions should go to, then message me again.',\n ),\n Actions([\n LinkButton({\n url: `${publicUrl}/settings/connections`,\n label: 'Open settings',\n }),\n ]),\n ],\n }),\n { fallbackToDM: true },\n );\n }\n return { status: 'blocked' };\n}\n\n/**\n * Deterministic per-thread branch name: `slack/{threadTs}` with characters\n * outside the sandbox git-ref allow-list (`[A-Za-z0-9_./-]`, and `.` for\n * readability) mapped to `-`. `thread.id` is `{channelId}:{threadTs}`\n * (platform-prefixed on handler threads) — the trailing segment is the ts.\n */\nfunction threadBranch(threadId: string): string {\n const ts = threadId.split(':').at(-1) ?? threadId;\n return `slack/${ts.replace(/[^A-Za-z0-9_/-]/g, '-')}`;\n}\n\n/**\n * Resolve the resourceId for a NEW Slack channel thread. A linked sender whose\n * factory has a repository gets a Factory user-session id — the controller\n * session then materializes the repo sandbox via the factory's dynamic\n * workspace (clone + PAT), the session shows up in the web Sessions list, and\n * View Session deep-links land on the normal workspace route. Everything else\n * (unlinked, unrouted, repo-less, or no source control) keeps the chat-only\n * `defaultResourceId`.\n *\n * Pure lookups only — cards for unlinked/unrouted senders are the dispatch\n * gate's job; this hook must never post.\n */\nexport function createChannelResourceIdResolver(deps: SlackChannelDeps): ResolveResourceId {\n const { accountLinks, projects, sourceControl } = deps;\n return async ({ platform, thread, message }) => {\n // NOT the hook's `defaultResourceId`: configuring a custom resolver\n // bypasses AgentControllerChannels' own `channel:{thread.id}` derivation\n // (agent-controller-channels.ts `resolveChannelResourceId`), and the base\n // default is the per-USER memory key. Chat-only fallbacks must stay\n // per-thread, so reproduce the controller default here.\n const chatOnlyResourceId = `channel:${thread.id}`;\n if (!accountLinks || !projects || !sourceControl) return chatOnlyResourceId;\n try {\n const externalTeamId = rawTeamId(message.raw);\n if (!externalTeamId) return chatOnlyResourceId;\n const link = await accountLinks.getAccountLink({\n platform,\n externalTeamId,\n externalUserId: message.author.userId,\n });\n if (!link) return chatOnlyResourceId;\n\n // Same chain as `resolveFactoryForLink`, minus prompts/stamping: the\n // dispatch gate has already run (and stamped a lone factory) by the\n // time a new thread is created, so this is a read-only re-resolve.\n const orgId = link.orgId ?? '';\n let factoryProjectId: string | undefined;\n if (link.defaultFactoryProjectId && (await projects.get({ orgId, id: link.defaultFactoryProjectId }))) {\n factoryProjectId = link.defaultFactoryProjectId;\n } else if (orgId) {\n const factories = await projects.list({ orgId });\n if (factories.length === 1) factoryProjectId = factories[0]!.id;\n }\n if (!factoryProjectId) return chatOnlyResourceId;\n\n const repo = await resolveFactorySourceRepository({ sourceControl, orgId, factoryProjectId });\n if (!repo.found) return chatOnlyResourceId;\n\n const branch = threadBranch(thread.id);\n // Attributed to the Slack sender, not to whoever connected the repository:\n // unlike an autonomous rule run, a Slack thread has a real interactive user.\n const existing = await sourceControl.sessions.getForBranch({\n projectRepositoryId: repo.projectRepositoryId,\n userId: link.userId,\n branch,\n });\n if (existing) return existing.sessionId;\n const session = await sourceControl.sessions.create({\n sessionId: randomUUID(),\n projectRepositoryId: repo.projectRepositoryId,\n orgId,\n userId: link.userId,\n branch,\n baseBranch: repo.baseBranch,\n });\n return session.sessionId;\n } catch (error) {\n // Fall back to a chat-only session rather than dropping the message.\n console.warn('[slack] repo-backed session resolution failed for thread', thread.id, error);\n return chatOnlyResourceId;\n }\n };\n}\n\n/**\n * Thread id for a NEW Slack channel thread. Repo-backed threads take the\n * user-session id AS their thread id, matching the web convention\n * (FactoryStartCoordinator seeds threads with threadId = sessionId) so\n * `/workspaces/{sessionId}/threads/{sessionId}` resolves Slack-created\n * sessions exactly like web-created ones — no `?resourceId=` override needed.\n * Chat-only threads keep the default random id: their `channel:...`\n * resourceId is a memory key, not a unique thread id.\n */\nexport const resolveChannelThreadId: ResolveThreadId = ({ resourceId, defaultThreadId }) =>\n resourceId.startsWith('channel:') ? defaultThreadId : resourceId;\n\n/**\n * Apply the factory's configuration to a Slack-created session the first time\n * its thread reaches the controller.\n *\n * Without this a Slack session runs on the SDK's built-in mode default\n * (`openai/gpt-5.5`), so a factory configured for any other provider fails every\n * message with a missing-credentials error. The web kickoff has always applied\n * the factory default; this brings Slack to the same footing.\n *\n * Only repo-backed threads are configured. Their resourceId IS the Factory\n * session id, which the source-control rows turn back into a project — a\n * chat-only `channel:...` id names no project, so there is nothing to read.\n *\n * Skips a session whose mode already has a model persisted on the thread. That\n * is the durable record of a deliberate choice — either an earlier start or a\n * user's own switch — and re-applying the factory default over it would undo\n * the user's selection every time the process restarts.\n */\nexport function createChannelSessionStartHook(deps: SlackChannelDeps): ChannelSessionStart {\n const { projects, sourceControl, memorySettings } = deps;\n return async ({ session, thread }) => {\n if (!projects || !sourceControl) return;\n if (thread.resourceId.startsWith('channel:')) return;\n\n const modeModelKey = `modeModelId_${session.mode.get()}`;\n if (await session.thread.getSetting({ key: modeModelKey })) return;\n\n const owner = await resolveFactoryProjectForSession({ sourceControl, sessionId: thread.resourceId });\n if (!owner) return;\n\n const defaultModelId = await resolveFactoryDefaultModelId(projects, owner.factoryProjectId);\n await hydrateFactorySession(session, {\n orgId: owner.orgId,\n userId: owner.userId,\n defaultModelId,\n memorySettings,\n });\n };\n}\n\n/**\n * The internal Mastra thread the framework created for a channel conversation.\n * The handler's `thread.id` is the platform thread id (e.g. `slack:C123:ts`),\n * NOT the internal UUID — the mapping lives in the stored thread's channel\n * metadata.\n */\nasync function findInternalThread(mastra: Mastra | undefined, thread: HandlerThread) {\n const store = await mastra?.getStorage()?.getStore('memory');\n const { threads } = (await store?.listThreads({\n filter: {\n metadata: {\n channel_platform: thread.adapter.name,\n channel_externalThreadId: thread.id,\n channel_externalChannelId: thread.channelId,\n },\n },\n perPage: 1,\n })) ?? { threads: [] };\n return threads[0];\n}\n\n/**\n * Build the \"new session\" handler for mention / direct-message events. A mention or\n * DM on a not-yet-subscribed thread starts a NEW session; once subscribed, later\n * events are follow-ups and don't re-announce.\n */\n/**\n * Run the account-link + factory-routing gates for one inbound message.\n * Returns `null` when the run must not dispatch (a prompt card was posted\n * where possible); otherwise the dispatch context — with `routed` present\n * only when a linked sender resolved to a factory.\n */\nasync function gateDispatch(\n thread: HandlerThread,\n message: HandlerMessage,\n { accountLinks, projects }: SlackChannelDeps,\n ctx: ChannelHandlerContext,\n): Promise<{\n routed?: { link: ChannelAccountLink; factoryProjectId: string; slackWorkItemsEnabled: boolean };\n} | null> {\n const sender = await resolveLinkedSender({ thread, message, accountLinks });\n if (sender.status === 'blocked') return null;\n // Linked senders must also route to a Factory project before a run starts.\n if (sender.status === 'linked' && accountLinks) {\n // Stamp the tenant on the run's request context — the single seam\n // `resolveCredentialStore` reads to load this sender's model credentials.\n // This belongs to the link, not to the routing: a linked sender whose\n // factory routing comes back `ungated` still exits below and dispatches, so\n // stamping only in the routed branch would silently run them on default\n // credentials.\n ctx.requestContext.set('user', { id: sender.link.userId, organizationId: sender.link.orgId });\n\n const route = await resolveFactoryForLink({ thread, message, ...sender, accountLinks, projects });\n if (route.status === 'blocked') return null;\n if (route.status === 'resolved') {\n return {\n routed: {\n link: sender.link,\n factoryProjectId: route.factoryProjectId,\n slackWorkItemsEnabled: route.slackWorkItemsEnabled,\n },\n };\n }\n }\n return {};\n}\n\n/**\n * Upsert the Work-board card for a dispatched Slack-thread run. Keyed on the\n * thread via `externalSource` — the work-items domain's unique\n * `(factory_project_id, source_key)` index makes repeat messages reuse the\n * same card, and `reuseMode: 'preserve'` keeps a card a human already dragged\n * across stages untouched. The card lands in Building (`execute`) for every\n * dispatched thread (DM or mention) — there is deliberately no per-origin\n * stage split; smart routing is a follow-up.\n *\n * The session id / branch / threadId and the workspace deep-link are resolved\n * by the caller (which already looked up the internal thread), so this helper\n * just shapes and writes. Best-effort: the run is already dispatched, so a\n * failure logs instead of throwing — work-item creation must never abort a Slack run.\n */\nexport async function upsertThreadWorkItem({\n workItems,\n thread,\n message,\n link,\n factoryProjectId,\n session,\n url,\n}: {\n workItems: WorkItemsStorage;\n thread: HandlerThread;\n message: HandlerMessage;\n link: ChannelAccountLink;\n factoryProjectId: string;\n /**\n * The repo-backed Factory session to bind under the `chat` role, or\n * `undefined` for a chat-only thread (no Factory session to bind).\n */\n session?: { sessionId: string; branch: string; threadId: string };\n /** Workspace deep-link to the running session; omitted when no public URL. */\n url?: string;\n}): Promise<void> {\n try {\n const title = message.text.length > 80 ? `${message.text.slice(0, 79)}…` : message.text;\n\n await workItems.upsert({\n orgId: link.orgId ?? '',\n userId: link.userId,\n factoryProjectId,\n reuseMode: 'preserve',\n input: {\n title: title || 'Slack thread',\n // `integrationId` is the platform ('slack'); `type` is a single\n // constant (no DM/mention distinction); `externalId` is the stable\n // platform thread id — together they form the idempotency key.\n externalSource: {\n integrationId: thread.adapter.name,\n type: 'slack-thread',\n externalId: thread.id,\n ...(url ? { url } : {}),\n },\n stages: ['execute'],\n ...(session ? { sessions: { chat: session } } : {}),\n },\n });\n } catch (error) {\n console.warn('[slack] work-item creation failed for thread', thread.id, error);\n }\n}\n\nfunction createNewSessionChatHandler(deps: SlackChannelDeps): ChannelHandler {\n const { workItems } = deps;\n return async (thread, message, defaultHandler, ctx) => {\n // Gate on the sender having linked their Slack account to a Mastra tenant.\n // Unlinked → post the ephemeral Connect card and stop; no session/run is\n // created (which would otherwise be tenant-less and fail credential\n // resolution). This handler is the only gate — core dispatches whatever\n // reaches it — so every slot that can start a run must call it.\n const gate = await gateDispatch(thread, message, deps, ctx);\n if (!gate) return;\n\n // A mention on a not-yet-subscribed thread is a NEW session. The\n // default handler auto-subscribes, so once subscribed this is a\n // follow-up mention — don't re-announce.\n const isNewSession = !(await thread.isSubscribed());\n\n // Run the framework handler first so the internal Mastra thread and\n // controller session are created before we build the deep link.\n await defaultHandler(thread, message);\n\n if (!isNewSession) return;\n\n // The internal-thread lookup and deep-link are needed by BOTH the\n // announcement card AND work-item creation, so they run BEFORE the\n // card-only `MASTRACODE_PUBLIC_URL` gate — a deployment without a public\n // origin should still create board cards, just without a clickable link.\n const internalThread = await findInternalThread(ctx.mastra, thread);\n if (!internalThread) {\n console.warn('[onMention] no internal thread found for', thread.id);\n return;\n }\n\n // When the sender routed to a factory we know exactly which workspace the\n // session belongs to — deep-link straight into it. A repo-backed thread's\n // resourceId IS the Factory user-session id, so the link lands on the same\n // route a web-started run navigates to; chat-only threads keep the literal\n // `channel` segment (the real resource rides the `?resourceId=` override).\n // Unrouted senders fall back to the factory-agnostic /threads/ redirect.\n // One predicate drives both the path segment and the query param, so the\n // two can never disagree about what the URL already carries.\n const isChatOnly = internalThread.resourceId.startsWith('channel:');\n const workspaceSegment = isChatOnly ? 'channel' : encodeURIComponent(internalThread.resourceId);\n const threadPath = gate.routed\n ? `/factories/${encodeURIComponent(gate.routed.factoryProjectId)}/workspaces/${workspaceSegment}/threads/${encodeURIComponent(internalThread.id)}`\n : `/threads/${internalThread.id}`;\n\n // The param is an override for a URL that can't otherwise name its\n // resource. A routed repo-backed thread already spells the resourceId out\n // as its workspace segment, so appending it again is duplication the app\n // ignores. Chat-only threads need it (their segment is the literal string\n // `channel`), and so does the unrouted fallback, which has no workspace\n // segment at all — `ChannelThreadRedirect` forwards the search through.\n //\n // One shared deep-link: the card's button and the work-item `url` read the\n // SAME value so they can never drift. Undefined without a public origin —\n // the card is then skipped, but the work item is still created (url omitted).\n const needsResourceParam = isChatOnly || !gate.routed;\n const deepLink = process.env.MASTRACODE_PUBLIC_URL\n ? needsResourceParam\n ? `${process.env.MASTRACODE_PUBLIC_URL}${threadPath}?resourceId=${encodeURIComponent(internalThread.resourceId)}`\n : `${process.env.MASTRACODE_PUBLIC_URL}${threadPath}`\n : undefined;\n\n // A dispatched, routed new-session thread becomes a Work-board card in\n // Building. Only routed senders (linked → factory) have the org/user/factory\n // a work item needs. Bind the repo-backed Factory session under the `chat`\n // role; a chat-only `channel:` resourceId is NOT a session id, so bind\n // nothing rather than a bad id. Best-effort (the helper swallows failures).\n if (workItems && gate.routed?.slackWorkItemsEnabled) {\n const session = isChatOnly\n ? undefined\n : { sessionId: internalThread.resourceId, branch: threadBranch(thread.id), threadId: internalThread.id };\n await upsertThreadWorkItem({\n workItems,\n thread,\n message,\n link: gate.routed.link,\n factoryProjectId: gate.routed.factoryProjectId,\n session,\n url: deepLink,\n });\n }\n\n // The announcement card is only useful with a public origin to deep-link\n // to — otherwise the link would be `undefined/threads/...`. Without one the\n // session (and now the work item) still exist; we just skip the broken card.\n if (!deepLink) return;\n\n await thread.post(\n Card({\n title: 'New session started',\n children: [Actions([LinkButton({ url: deepLink, label: 'View session' })])],\n }),\n );\n };\n}\nexport const createHandlers = (deps: SlackChannelDeps): ChannelHandlers => {\n const newSessionChatHandler = createNewSessionChatHandler(deps);\n\n return {\n onSubscribedMessage: async (thread, message, defaultHandler, ctx) => {\n // `aside` as its own leading word lets humans talk in a subscribed\n // thread without the bot replying. Word boundary so messages that\n // merely start with \"aside...\" (e.g. \"asides can wait\") still route.\n if (/^aside\\b/i.test(message.text)) return;\n // A subscribed follow-up from an unlinked sender must not run either\n // (e.g. the link was removed mid-conversation), and it must still\n // resolve a factory (e.g. the default was cleared or its factory\n // deleted mid-conversation).\n const gate = await gateDispatch(thread, message, deps, ctx);\n if (!gate) return;\n await defaultHandler(thread, message);\n },\n onMention: newSessionChatHandler,\n onDirectMessage: newSessionChatHandler,\n };\n};\n\n/** Slack app credentials, passed in explicitly rather than read from env here. */\ninterface SlackCredentials {\n clientId?: string;\n clientSecret?: string;\n signingSecret: string;\n botToken?: string;\n}\n\nexport function createSlackChannelsConfig(deps: SlackChannelDeps & { slack: SlackCredentials }): FactoryChannelsConfig {\n return {\n adapters: {\n slack: {\n adapter: createSlackAdapter(deps.slack),\n toolDisplay: 'hidden',\n },\n },\n handlers: createHandlers(deps),\n // New linked+repo-backed threads own a Factory user-session id as their\n // resourceId, which is what makes the controller session repo-backed.\n resolveResourceId: createChannelResourceIdResolver(deps),\n resolveThreadId: resolveChannelThreadId,\n // Those sessions are created by the channel machinery, not the web kickoff,\n // so this is where they pick up the factory's configuration.\n onSessionStart: createChannelSessionStartHook(deps),\n };\n}\n"],"mappings":";;;;;;;;;;AAyFA,SAAS,UAAU,YAAyC;CAC1D,IAAI,CAAC,cAAc,OAAO,eAAe,UAAU,OAAO,KAAA;CAC1D,MAAM,MAAM;CACZ,IAAI,OAAO,IAAI,YAAY,YAAY,IAAI,SAAS,OAAO,IAAI;CAC/D,IAAI,OAAO,IAAI,SAAS,YAAY,IAAI,MAAM,OAAO,IAAI;CACzD,IAAI,IAAI,QAAQ,OAAO,IAAI,SAAS,UAAU;EAC5C,MAAM,KAAM,IAAI,KAA0B;EAC1C,IAAI,OAAO,OAAO,YAAY,IAAI,OAAO;CAC3C;AAEF;;;;;AAMA,SAAS,YAAY,SAA6C;CAChE,OAAO,UAAU,QAAQ,GAAG;AAC9B;;;;;;;AAQA,SAAS,eAAmC;CAC1C,OAAO,QAAQ,IAAI,yBAAyB,QAAQ,IAAI;AAC1D;;;;;;AAgBA,eAAsB,oBAAoB,EACxC,QACA,SACA,gBAK8B;CAC9B,IAAI,CAAC,cAAc,OAAO,EAAE,QAAQ,UAAU;CAC9C,MAAM,WAAW,OAAO,QAAQ;CAChC,MAAM,iBAAiB,QAAQ,OAAO;CACtC,MAAM,iBAAiB,YAAY,OAAO;CAG1C,MAAM,M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,QAAQ,CAAC,WAAW;IAAE,KAAK;IAAU,OAAO;GAAe,CAAC,CAAC,CAAC,CAAC;EAC5E,CAAC,CACH;CACF;AACF;AACA,MAAa,kBAAkB,SAA4C;CACzE,MAAM,wBAAwB,4BAA4B,IAAI;CAE9D,OAAO;EACL,qBAAqB,OAAO,QAAQ,SAAS,gBAAgB,QAAQ;GAInE,IAAI,YAAY,KAAK,QAAQ,IAAI,GAAG;GAMpC,IAAI,CAAC,MADc,aAAa,QAAQ,SAAS,MAAM,GAAG,GAC/C;GACX,MAAM,eAAe,QAAQ,OAAO;EACtC;EACA,WAAW;EACX,iBAAiB;CACnB;AACF;AAUA,SAAgB,0BAA0B,MAA6E;CACrH,OAAO;EACL,UAAU,EACR,OAAO;GACL,SAAS,mBAAmB,KAAK,KAAK;GACtC,aAAa;EACf,EACF;EACA,UAAU,eAAe,IAAI;EAG7B,mBAAmB,gCAAgC,IAAI;EACvD,iBAAiB;EAGjB,gBAAgB,8BAA8B,IAAI;CACpD;AACF"}
@@ -4,7 +4,9 @@ import type { AgentController } from '@mastra/core/agent-controller';
4
4
  import type { ApiRoute } from '@mastra/core/server';
5
5
  import type { FactoryStorage } from '@mastra/core/storage';
6
6
  import type { FactoryIntegration, IntegrationContext } from '../integrations/base.js';
7
+ import type { GithubIntegration } from '../integrations/github/integration.js';
7
8
  import type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';
9
+ import { FactoryStartCoordinator } from '../rules/start-coordinator.js';
8
10
  import { FactoryTransitionService } from '../rules/transition-service.js';
9
11
  import type { FactoryRules } from '../rules/types.js';
10
12
  import type { SandboxFleet } from '../sandbox/fleet.js';
@@ -67,6 +69,14 @@ export interface FactoryApiRoutesDeps {
67
69
  }) => void;
68
70
  }
69
71
  export declare function factoryRuleBranch(item: FactoryBindingPreparationInput['item']): string;
72
+ /**
73
+ * Start a factory run for a rule binding: ensure the source-control session the
74
+ * coordinator requires, then hand it to `prepare` along with the factory's
75
+ * default model. Exported for tests — this is the autonomous entry point with no
76
+ * browser and no interactive user, so nothing else would catch a regression in
77
+ * what it forwards.
78
+ */
79
+ export declare function prepareFactoryRuleBinding(github: GithubIntegration, coordinator: FactoryStartCoordinator, projects: FactoryProjectsStorage, input: FactoryBindingPreparationInput): Promise<void>;
70
80
  /**
71
81
  * Build the {@link IntegrationContext} handed to an integration when the
72
82
  * factory collects its capabilities (routes, workers). One shape everywhere:
@@ -78,7 +88,7 @@ export declare function buildIntegrationContext(deps: Pick<FactoryApiRoutesDeps,
78
88
  emitAudit?: AuditEmitter['emit'];
79
89
  rules: FactoryRules;
80
90
  factoryReady: boolean;
81
- domains: Pick<FactoryApiRoutesDeps['domains'], 'projects' | 'intake' | 'workItems' | 'channelIdentity'>;
91
+ domains: Pick<FactoryApiRoutesDeps['domains'], 'projects' | 'intake' | 'workItems' | 'channelIdentity' | 'memorySettings'>;
82
92
  /**
83
93
  * Stable id of the registered source-control-owning integration (today:
84
94
  * `'github'` when registered). Every call site must derive and pass it so
@@ -1 +1 @@
1
- {"version":3,"file":"surface.d.ts","sourceRoot":"","sources":["../../src/routes/surface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAItF,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,wBAAwB,CAAC;AAE7E,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,O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AO,CAAC,IAAI,CAAC,CAoCf;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,IAAI,CACR,oBAAoB,EACpB,YAAY,GAAG,cAAc,GAAG,MAAM,GAAG,OAAO,GAAG,gBAAgB,GAAG,oBAAoB,GAAG,sBAAsB,CACpH,GAAG;IACF,WAAW,EAAE,WAAW,CAAC;IACzB,SAAS,CAAC,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;IACjC,KAAK,EAAE,YAAY,CAAC;IACpB,YAAY,EAAE,OAAO,CAAC;IACtB,OAAO,EAAE,IAAI,CACX,oBAAoB,CAAC,SAAS,CAAC,EAC/B,UAAU,GAAG,QAAQ,GAAG,WAAW,GAAG,iBAAiB,GAAG,gBAAgB,CAC3E,CAAC;IACF;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B,EACD,aAAa,EAAE,MAAM,GACpB,kBAAkB,CAsBpB;AA4ED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,oBAAoB,GAAG,QAAQ,EAAE,CAkH/E"}
@@ -1,6 +1,6 @@
1
+ import { ensureFactorySourceSession, resolveFactoryDefaultModelId } from "../session/factory-session.js";
1
2
  import { getGithubFeatureDiagnostics } from "../integrations/github/config.js";
2
3
  import { invalidateCustomProvidersSnapshots } from "./custom-provider-source.js";
3
- import { ensureFactoryRuleSession } from "../integrations/github/factory-session.js";
4
4
  import { FactoryStartCoordinator } from "../rules/start-coordinator.js";
5
5
  import { FactoryTransitionService } from "../rules/transition-service.js";
6
6
  import { ConfigRoutes } from "./config.js";
@@ -58,13 +58,21 @@ function factoryRuleBranch(item) {
58
58
  if (item.externalSource?.integrationId === "github" && item.externalSource.type === "issue" && typeof issueNumber === "number") return `factory/issue-${issueNumber}`;
59
59
  const pullRequestNumber = metadata.githubPullRequestNumber ?? metadata.number;
60
60
  if (item.externalSource?.integrationId === "github" && item.externalSource.type === "pull-request" && typeof pullRequestNumber === "number") return `factory/pr-${pullRequestNumber}`;
61
- throw new Error("Factory skill invocation requires a GitHub issue or pull request number.");
61
+ if (item.externalSource?.integrationId === "linear" && typeof metadata.identifier === "string") return `factory/linear-${metadata.identifier.toLowerCase()}`;
62
+ throw new Error("Factory skill invocation requires a supported issue or pull request identifier.");
62
63
  }
63
- async function prepareFactoryRuleBinding(github, coordinator, input) {
64
+ /**
65
+ * Start a factory run for a rule binding: ensure the source-control session the
66
+ * coordinator requires, then hand it to `prepare` along with the factory's
67
+ * default model. Exported for tests — this is the autonomous entry point with no
68
+ * browser and no interactive user, so nothing else would catch a regression in
69
+ * what it forwards.
70
+ */
71
+ async function prepareFactoryRuleBinding(github, coordinator, projects, input) {
64
72
  const branch = factoryRuleBranch(input.item);
65
73
  const repositorySlug = typeof input.item.metadata?.repository === "string" ? input.item.metadata.repository : void 0;
66
- const preparedSession = await ensureFactoryRuleSession({
67
- github,
74
+ const preparedSession = await ensureFactorySourceSession({
75
+ sourceControl: github.sourceControlStorage,
68
76
  orgId: input.record.orgId,
69
77
  factoryProjectId: input.record.factoryProjectId,
70
78
  repositorySlug,
@@ -77,6 +85,7 @@ async function prepareFactoryRuleBinding(github, coordinator, input) {
77
85
  userId: preparedSession.userId,
78
86
  factoryProjectId: input.record.factoryProjectId,
79
87
  sessionId: preparedSession.sessionId,
88
+ defaultModelId: await resolveFactoryDefaultModelId(projects, input.record.factoryProjectId),
80
89
  threadTitle: `${input.role === "review" ? "PR" : "Issue"}: ${input.item.title}`,
81
90
  kickoffKey: input.record.id,
82
91
  destinationStage,
@@ -114,7 +123,8 @@ function buildIntegrationContext(deps, integrationId) {
114
123
  ...deps.sourceControlOwnerId ? { sourceControlOwner: deps.sourceControlStorage.forIntegration(deps.sourceControlOwnerId) } : {},
115
124
  projects: deps.domains.projects,
116
125
  intake: deps.domains.intake,
117
- channelIdentity: deps.domains.channelIdentity
126
+ channelIdentity: deps.domains.channelIdentity,
127
+ memorySettings: deps.domains.memorySettings
118
128
  },
119
129
  ...deps.factoryReady ? { rules: {
120
130
  config: deps.rules,
@@ -223,7 +233,7 @@ function assembleFactoryApiRoutes(deps) {
223
233
  const startCoordinator = transitionService ? new FactoryStartCoordinator(deps.controller, deps.domains.workItems, transitionService, githubIntegration?.sourceControlStorage, deps.domains.memorySettings) : void 0;
224
234
  if (transitionService && startCoordinator) deps.onFactoryRuntime?.({
225
235
  transitionService,
226
- ...githubIntegration ? { prepareBinding: (input) => prepareFactoryRuleBinding(githubIntegration, startCoordinator, input) } : {}
236
+ ...githubIntegration ? { prepareBinding: (input) => prepareFactoryRuleBinding(githubIntegration, startCoordinator, deps.domains.projects, input) } : {}
227
237
  });
228
238
  return [
229
239
  ...buildFsRoutes({
@@ -282,6 +292,6 @@ function assembleFactoryApiRoutes(deps) {
282
292
  ];
283
293
  }
284
294
  //#endregion
285
- export { assembleFactoryApiRoutes, buildIntegrationContext, factoryRuleBranch };
295
+ export { assembleFactoryApiRoutes, buildIntegrationContext, factoryRuleBranch, prepareFactoryRuleBinding };
286
296
 
287
297
  //# sourceMappingURL=surface.js.map