@mastra/factory 0.24.0-alpha.9 → 0.25.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -13
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +18 -4
- package/dist/auth.js.map +1 -1
- package/dist/boards/review.d.ts.map +1 -1
- package/dist/boards/review.js +3 -2
- package/dist/boards/review.js.map +1 -1
- package/dist/environment/build-runner.js +2 -1
- package/dist/environment/build-runner.js.map +1 -1
- package/dist/environment/build-workflow.js +1 -1
- package/dist/environment/build-workflow.js.map +1 -1
- package/dist/environment/build.js +16 -14
- package/dist/environment/build.js.map +1 -1
- package/dist/factory.d.ts +3 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +172 -88
- package/dist/factory.js.map +1 -1
- package/dist/integrations/base.d.ts +15 -2
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/github/app-identity.js.map +1 -1
- package/dist/integrations/github/integration.js +1 -1
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/reconcile-worker.js +1 -1
- package/dist/integrations/github/reconcile-worker.js.map +1 -1
- package/dist/integrations/github/routes.d.ts +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +24 -13
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +53 -9
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.js +2 -2
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/github/session-subscriptions.d.ts.map +1 -1
- package/dist/integrations/github/session-subscriptions.js +1 -2
- package/dist/integrations/github/session-subscriptions.js.map +1 -1
- package/dist/integrations/github/subscriptions.d.ts +7 -4
- package/dist/integrations/github/subscriptions.d.ts.map +1 -1
- package/dist/integrations/github/subscriptions.js +5 -5
- package/dist/integrations/github/subscriptions.js.map +1 -1
- package/dist/integrations/gitlab/api.js.map +1 -1
- package/dist/integrations/gitlab/integration.js.map +1 -1
- package/dist/integrations/gitlab/reconciliation-config.js +2 -1
- package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
- package/dist/integrations/gitlab/routes.d.ts.map +1 -1
- package/dist/integrations/gitlab/routes.js +10 -6
- package/dist/integrations/gitlab/routes.js.map +1 -1
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/gitlab/session-subscriptions.d.ts.map +1 -1
- package/dist/integrations/gitlab/session-subscriptions.js +1 -2
- package/dist/integrations/gitlab/session-subscriptions.js.map +1 -1
- package/dist/integrations/gitlab/subscriptions.d.ts +7 -4
- package/dist/integrations/gitlab/subscriptions.d.ts.map +1 -1
- package/dist/integrations/gitlab/subscriptions.js +5 -5
- package/dist/integrations/gitlab/subscriptions.js.map +1 -1
- package/dist/integrations/incidentio/api.js.map +1 -1
- package/dist/integrations/incidentio/integration.js.map +1 -1
- package/dist/integrations/incidentio/rules.js.map +1 -1
- package/dist/integrations/issue-reconcile-worker.js +1 -1
- package/dist/integrations/issue-reconcile-worker.js.map +1 -1
- package/dist/integrations/issue-reconciler.js +1 -1
- package/dist/integrations/issue-reconciler.js.map +1 -1
- package/dist/integrations/jira/api.js.map +1 -1
- package/dist/integrations/jira/integration.js.map +1 -1
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
- package/dist/integrations/linear/agent-tools.js.map +1 -1
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/platform/api-client.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +1 -1
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.js +2 -2
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
- package/dist/integrations/platform/gitlab/integration.js.map +1 -1
- package/dist/integrations/platform/incidentio/integration.js +2 -1
- package/dist/integrations/platform/incidentio/integration.js.map +1 -1
- package/dist/integrations/platform/jira/integration.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.js +1 -1
- package/dist/integrations/platform/linear/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/{session → integrations/slack}/channel-reply-processor.d.ts +11 -9
- package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -0
- package/dist/integrations/slack/channel-reply-processor.js +61 -0
- package/dist/integrations/slack/channel-reply-processor.js.map +1 -0
- package/dist/integrations/slack/channel-session-link-processor.d.ts.map +1 -0
- package/dist/{session → integrations/slack}/channel-session-link-processor.js +14 -4
- package/dist/integrations/slack/channel-session-link-processor.js.map +1 -0
- package/dist/integrations/slack/connect-route.js +1 -1
- package/dist/integrations/slack/connect-route.js.map +1 -1
- package/dist/integrations/slack/feed-publisher.js +1 -1
- package/dist/integrations/slack/feed-publisher.js.map +1 -1
- package/dist/integrations/slack/integration.d.ts +25 -1
- package/dist/integrations/slack/integration.d.ts.map +1 -1
- package/dist/integrations/slack/integration.js +56 -6
- package/dist/integrations/slack/integration.js.map +1 -1
- package/dist/integrations/slack/reply-reminder-processor.d.ts +23 -0
- package/dist/integrations/slack/reply-reminder-processor.d.ts.map +1 -0
- package/dist/integrations/slack/reply-reminder-processor.js +58 -0
- package/dist/integrations/slack/reply-reminder-processor.js.map +1 -0
- package/dist/integrations/slack/reply-tool.d.ts +31 -0
- package/dist/integrations/slack/reply-tool.d.ts.map +1 -0
- package/dist/integrations/slack/reply-tool.js +203 -0
- package/dist/integrations/slack/reply-tool.js.map +1 -0
- package/dist/integrations/slack/share-file-tool.d.ts +45 -0
- package/dist/integrations/slack/share-file-tool.d.ts.map +1 -0
- package/dist/integrations/slack/share-file-tool.js +106 -0
- package/dist/integrations/slack/share-file-tool.js.map +1 -0
- package/dist/integrations/slack/slack.d.ts +16 -5
- package/dist/integrations/slack/slack.d.ts.map +1 -1
- package/dist/integrations/slack/slack.js +141 -40
- package/dist/integrations/slack/slack.js.map +1 -1
- package/dist/integrations/subscription-session.d.ts +0 -1
- package/dist/integrations/subscription-session.d.ts.map +1 -1
- package/dist/integrations/subscription-session.js +1 -4
- package/dist/integrations/subscription-session.js.map +1 -1
- package/dist/integrations/workos/integration.js.map +1 -1
- package/dist/mcp/events.d.ts +73 -0
- package/dist/mcp/events.d.ts.map +1 -0
- package/dist/mcp/events.js +158 -0
- package/dist/mcp/events.js.map +1 -0
- package/dist/mcp/routes.d.ts +0 -1
- package/dist/mcp/routes.d.ts.map +1 -1
- package/dist/mcp/routes.js +31 -4
- package/dist/mcp/routes.js.map +1 -1
- package/dist/packages/_internals/workspace/dist/index.js +18 -1
- package/dist/packages/_internals/workspace/dist/index.js.map +1 -1
- package/dist/platform-auth-host.d.ts.map +1 -1
- package/dist/platform-auth-host.js +1 -1
- package/dist/platform-auth-host.js.map +1 -1
- package/dist/routes/attention-activity.js.map +1 -1
- package/dist/routes/attention-parked.js.map +1 -1
- package/dist/routes/attention-providers.js.map +1 -1
- package/dist/routes/automation-runs.js.map +1 -1
- package/dist/routes/config.d.ts +8 -7
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +70 -28
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/contracts.d.ts +2 -0
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +2 -2
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/custom-provider-source.js.map +1 -1
- package/dist/routes/fs.d.ts +31 -23
- package/dist/routes/fs.d.ts.map +1 -1
- package/dist/routes/fs.js +218 -64
- package/dist/routes/fs.js.map +1 -1
- package/dist/routes/intake.js +2 -1
- package/dist/routes/intake.js.map +1 -1
- package/dist/routes/knowledge.js +1 -1
- package/dist/routes/knowledge.js.map +1 -1
- package/dist/routes/oauth.js +3 -2
- package/dist/routes/oauth.js.map +1 -1
- package/dist/routes/projects.d.ts +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +33 -31
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/provider-credentials.d.ts.map +1 -1
- package/dist/routes/provider-credentials.js +6 -1
- package/dist/routes/provider-credentials.js.map +1 -1
- package/dist/routes/session-access.d.ts +60 -0
- package/dist/routes/session-access.d.ts.map +1 -0
- package/dist/routes/session-access.js +202 -0
- package/dist/routes/session-access.js.map +1 -0
- package/dist/routes/skills.d.ts +2 -4
- package/dist/routes/skills.d.ts.map +1 -1
- package/dist/routes/skills.js +23 -68
- package/dist/routes/skills.js.map +1 -1
- package/dist/routes/source-control-sessions.d.ts +8 -1
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +239 -19
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/surface.d.ts +7 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +20 -8
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/tenant-credentials.js.map +1 -1
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/binding-context.js +11 -9
- package/dist/rules/binding-context.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +21 -13
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts +2 -2
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +3 -3
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/start-coordinator.d.ts +4 -0
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +36 -4
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/tools.js +2 -2
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/sandbox/callback-factory-sandbox.js.map +1 -1
- package/dist/sandbox/local-factory-sandbox.js.map +1 -1
- package/dist/sandbox/session-retirement.d.ts +11 -0
- package/dist/sandbox/session-retirement.d.ts.map +1 -1
- package/dist/sandbox/session-retirement.js +38 -1
- package/dist/sandbox/session-retirement.js.map +1 -1
- package/dist/sandbox/session-sandbox.d.ts +2 -0
- package/dist/sandbox/session-sandbox.d.ts.map +1 -1
- package/dist/sandbox/session-sandbox.js +5 -1
- package/dist/sandbox/session-sandbox.js.map +1 -1
- package/dist/secret-encryption.d.ts.map +1 -1
- package/dist/secret-encryption.js +65 -25
- package/dist/secret-encryption.js.map +1 -1
- package/dist/session/credential-policy.d.ts +4 -2
- package/dist/session/credential-policy.d.ts.map +1 -1
- package/dist/session/credential-policy.js +18 -7
- package/dist/session/credential-policy.js.map +1 -1
- package/dist/session/default-model-hydration.d.ts +1 -0
- package/dist/session/default-model-hydration.d.ts.map +1 -1
- package/dist/session/default-model-hydration.js +3 -2
- package/dist/session/default-model-hydration.js.map +1 -1
- package/dist/session/environment-state-processor.js +1 -1
- package/dist/session/environment-state-processor.js.map +1 -1
- package/dist/session/factory-session.d.ts.map +1 -1
- package/dist/session/factory-session.js +14 -1
- package/dist/session/factory-session.js.map +1 -1
- package/dist/session/filesystem-capture.d.ts +3 -3
- package/dist/session/filesystem-capture.d.ts.map +1 -1
- package/dist/session/filesystem-capture.js +16 -17
- package/dist/session/filesystem-capture.js.map +1 -1
- package/dist/session/first-exec-capture.d.ts +1 -1
- package/dist/session/first-exec-capture.d.ts.map +1 -1
- package/dist/session/first-exec-capture.js +1 -1
- package/dist/session/first-exec-capture.js.map +1 -1
- package/dist/session/first-message-capture.d.ts +1 -1
- package/dist/session/first-message-capture.d.ts.map +1 -1
- package/dist/session/first-message-capture.js +1 -1
- package/dist/session/first-message-capture.js.map +1 -1
- package/dist/session/live-sessions.d.ts +1 -1
- package/dist/session/live-sessions.js +1 -1
- package/dist/session/live-sessions.js.map +1 -1
- package/dist/session/memory-settings-hydration.d.ts +1 -1
- package/dist/session/memory-settings-hydration.d.ts.map +1 -1
- package/dist/session/memory-settings-hydration.js +2 -1
- package/dist/session/memory-settings-hydration.js.map +1 -1
- package/dist/session/resource-migration.d.ts +105 -0
- package/dist/session/resource-migration.d.ts.map +1 -0
- package/dist/session/resource-migration.js +195 -0
- package/dist/session/resource-migration.js.map +1 -0
- package/dist/session/run-audit.d.ts +1 -0
- package/dist/session/run-audit.d.ts.map +1 -1
- package/dist/session/run-audit.js +7 -2
- package/dist/session/run-audit.js.map +1 -1
- package/dist/session/session-threads.d.ts +63 -0
- package/dist/session/session-threads.d.ts.map +1 -0
- package/dist/session/session-threads.js +97 -0
- package/dist/session/session-threads.js.map +1 -0
- package/dist/session/source-control-tools.js +8 -8
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/session/thinking-default.d.ts +6 -13
- package/dist/session/thinking-default.d.ts.map +1 -1
- package/dist/session/thinking-default.js +19 -24
- package/dist/session/thinking-default.js.map +1 -1
- package/dist/session/thread-session-stamp.d.ts +21 -0
- package/dist/session/thread-session-stamp.d.ts.map +1 -0
- package/dist/session/thread-session-stamp.js +20 -0
- package/dist/session/thread-session-stamp.js.map +1 -0
- package/dist/session/thread-title-mirror.d.ts +1 -1
- package/dist/session/thread-title-mirror.d.ts.map +1 -1
- package/dist/session/thread-title-mirror.js +1 -1
- package/dist/session/thread-title-mirror.js.map +1 -1
- package/dist/session-owner-signal.d.ts +2 -0
- package/dist/session-owner-signal.d.ts.map +1 -0
- package/dist/session-owner-signal.js +6 -0
- package/dist/session-owner-signal.js.map +1 -0
- package/dist/skills/service.d.ts +11 -14
- package/dist/skills/service.d.ts.map +1 -1
- package/dist/skills/service.js +12 -22
- package/dist/skills/service.js.map +1 -1
- package/dist/spa-static.js.map +1 -1
- package/dist/state-signing.js +1 -1
- package/dist/state-signing.js.map +1 -1
- package/dist/storage/domains/audit/actions.d.ts +1 -0
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +2 -1
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/audit/agent-audit.d.ts.map +1 -1
- package/dist/storage/domains/audit/agent-audit.js +2 -2
- package/dist/storage/domains/audit/agent-audit.js.map +1 -1
- package/dist/storage/domains/audit/base.d.ts +18 -2
- package/dist/storage/domains/audit/base.d.ts.map +1 -1
- package/dist/storage/domains/audit/base.js +22 -4
- package/dist/storage/domains/audit/base.js.map +1 -1
- package/dist/storage/domains/audit/domain.js.map +1 -1
- package/dist/storage/domains/channel-identity/base.js.map +1 -1
- package/dist/storage/domains/comments/base.js.map +1 -1
- package/dist/storage/domains/comments/domain.js.map +1 -1
- package/dist/storage/domains/comments/feed-context.js.map +1 -1
- package/dist/storage/domains/credentials/base.js.map +1 -1
- package/dist/storage/domains/custom-providers/base.js.map +1 -1
- package/dist/storage/domains/intake/base.js.map +1 -1
- package/dist/storage/domains/integrations/base.d.ts +8 -0
- package/dist/storage/domains/integrations/base.d.ts.map +1 -1
- package/dist/storage/domains/integrations/base.js +7 -0
- package/dist/storage/domains/integrations/base.js.map +1 -1
- package/dist/storage/domains/memory-settings/base.js.map +1 -1
- package/dist/storage/domains/model-defaults/base.d.ts +8 -0
- package/dist/storage/domains/model-defaults/base.d.ts.map +1 -1
- package/dist/storage/domains/model-defaults/base.js +18 -0
- package/dist/storage/domains/model-defaults/base.js.map +1 -1
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/queue-health/base.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +44 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +109 -3
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +23 -1
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +35 -0
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +14 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +25 -1
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/board-version.js.map +1 -1
- package/dist/storage/domains/work-items/metrics.js.map +1 -1
- package/dist/tools/approval-tools.js +1 -1
- package/dist/tools/approval-tools.js.map +1 -1
- package/dist/tools/deliver.d.ts +8 -5
- package/dist/tools/deliver.d.ts.map +1 -1
- package/dist/tools/deliver.js +22 -8
- package/dist/tools/deliver.js.map +1 -1
- package/dist/tools/messaging-tools.d.ts +1 -1
- package/dist/tools/messaging-tools.d.ts.map +1 -1
- package/dist/tools/messaging-tools.js +203 -72
- package/dist/tools/messaging-tools.js.map +1 -1
- package/dist/tools/permissions.d.ts +1 -1
- package/dist/tools/permissions.d.ts.map +1 -1
- package/dist/tools/permissions.js +3 -2
- package/dist/tools/permissions.js.map +1 -1
- package/dist/tools/reports.d.ts.map +1 -1
- package/dist/tools/reports.js +10 -3
- package/dist/tools/reports.js.map +1 -1
- package/dist/tools/run-watch.d.ts +2 -0
- package/dist/tools/run-watch.d.ts.map +1 -1
- package/dist/tools/run-watch.js +42 -2
- package/dist/tools/run-watch.js.map +1 -1
- package/dist/tools/sandbox-tools.d.ts +12 -0
- package/dist/tools/sandbox-tools.d.ts.map +1 -0
- package/dist/tools/sandbox-tools.js +40 -0
- package/dist/tools/sandbox-tools.js.map +1 -0
- package/dist/tools/scope.d.ts +2 -1
- package/dist/tools/scope.d.ts.map +1 -1
- package/dist/tools/scope.js +5 -7
- package/dist/tools/scope.js.map +1 -1
- package/dist/tools/session-tools.d.ts +1 -1
- package/dist/tools/session-tools.d.ts.map +1 -1
- package/dist/tools/session-tools.js +39 -18
- package/dist/tools/session-tools.js.map +1 -1
- package/dist/tools/sessions-state-processor.js +2 -2
- package/dist/tools/sessions-state-processor.js.map +1 -1
- package/dist/tools/side-sessions.d.ts +1 -1
- package/dist/tools/side-sessions.d.ts.map +1 -1
- package/dist/tools/side-sessions.js +1 -1
- package/dist/tools/side-sessions.js.map +1 -1
- package/dist/work-item-branch.d.ts +11 -3
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +34 -9
- package/dist/work-item-branch.js.map +1 -1
- package/dist/workspace.d.ts +7 -3
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +32 -17
- package/dist/workspace.js.map +1 -1
- package/factory-skills/configure-factory-rules/SKILL.md +2 -2
- package/package.json +16 -15
- package/dist/session/channel-reply-processor.d.ts.map +0 -1
- package/dist/session/channel-reply-processor.js +0 -46
- package/dist/session/channel-reply-processor.js.map +0 -1
- package/dist/session/channel-session-link-processor.d.ts.map +0 -1
- package/dist/session/channel-session-link-processor.js.map +0 -1
- /package/dist/{session → integrations/slack}/channel-session-link-processor.d.ts +0 -0
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { actorFromChannelAuthor } from "../../storage/domains/comments/actor.js";
|
|
2
2
|
import { FACTORY_INTERACTIVE_KEY } from "../../auth.js";
|
|
3
|
+
import { isRunBound, memoryResourceOf, sessionStampCounts } from "../../session/session-threads.js";
|
|
3
4
|
import { primeTenantCredentialsForRequestContext, primeTenantCredentialsForTenant } from "../../routes/tenant-credentials.js";
|
|
4
5
|
import { readRequestContextOrgId, seedSessionOrg } from "../../session/org-seed.js";
|
|
5
6
|
import { prepareSessionRunContext } from "../subscription-session.js";
|
|
6
7
|
import { FactorySourceControlConflictError, createSourceControlSessionLookup, hydrateFactorySession, resolveFactorySessionModel, resolveFactorySourceControl, resolvePrimaryEnvironmentRepository } from "../../session/factory-session.js";
|
|
7
8
|
import { FACTORY_SLACK_SENDER_KEY } from "../../tools/scope.js";
|
|
8
|
-
import { markNewChannelSession } from "
|
|
9
|
+
import { markNewChannelSession } from "./channel-session-link-processor.js";
|
|
9
10
|
import { resolveEmojiShortcodes } from "./emoji.js";
|
|
10
11
|
import { slackCommentSource } from "./feed-publisher.js";
|
|
11
12
|
import { ChannelSessionRejectedError } from "@mastra/core/channels";
|
|
@@ -152,7 +153,11 @@ function threadBranch(threadId) {
|
|
|
152
153
|
}
|
|
153
154
|
/**
|
|
154
155
|
* Resolve the resourceId for a NEW Slack channel thread. A linked sender whose
|
|
155
|
-
* factory has a repository gets a Factory
|
|
156
|
+
* factory has a repository gets a Factory session. A channel thread belongs to
|
|
157
|
+
* the Factory: its resourceId is the Factory id, so the thread shares the
|
|
158
|
+
* Factory's memory. A DM is private to the sender, so it runs under the
|
|
159
|
+
* sender's user id and shares memory with their own sessions. The session id is recorded in `startedSessions` for the
|
|
160
|
+
* thread-id resolver. The controller
|
|
156
161
|
* session then materializes the repo sandbox via the factory's dynamic
|
|
157
162
|
* workspace (clone + PAT), the session shows up in the web Sessions list, and
|
|
158
163
|
* View Session deep-links land on the normal workspace route.
|
|
@@ -176,7 +181,7 @@ function threadBranch(threadId) {
|
|
|
176
181
|
* Pure lookups only — cards for unlinked/unrouted senders are the dispatch
|
|
177
182
|
* gate's job; this hook must never post.
|
|
178
183
|
*/
|
|
179
|
-
function createChannelResourceIdResolver(deps) {
|
|
184
|
+
function createChannelResourceIdResolver(deps, startedSessions = /* @__PURE__ */ new WeakMap()) {
|
|
180
185
|
const { accountLinks, projects } = deps;
|
|
181
186
|
const sourceControls = configuredSourceControls(deps);
|
|
182
187
|
return async ({ platform, thread, message }) => {
|
|
@@ -219,13 +224,17 @@ function createChannelResourceIdResolver(deps) {
|
|
|
219
224
|
});
|
|
220
225
|
if (!repo.found) throw new SlackSessionStartError(repo.reason === "connection" ? "Could not start a session: connect source control to this Factory project." : "Could not start a session: link a repository to this Factory project.");
|
|
221
226
|
const branch = threadBranch(thread.id);
|
|
227
|
+
const memoryResourceId = thread.isDM ? link.userId : factoryProjectId;
|
|
222
228
|
const existing = await sourceControl.sessions.getForBranch({
|
|
223
229
|
factoryProjectId,
|
|
224
230
|
userId: link.userId,
|
|
225
231
|
branch
|
|
226
232
|
});
|
|
227
|
-
if (existing)
|
|
228
|
-
|
|
233
|
+
if (existing) {
|
|
234
|
+
startedSessions.set(message, existing.sessionId);
|
|
235
|
+
return memoryResourceId;
|
|
236
|
+
}
|
|
237
|
+
const session = await sourceControl.sessions.create({
|
|
229
238
|
sessionId: globalThis.crypto.randomUUID(),
|
|
230
239
|
projectRepositoryId: repo.projectRepositoryId,
|
|
231
240
|
factoryProjectId,
|
|
@@ -234,7 +243,9 @@ function createChannelResourceIdResolver(deps) {
|
|
|
234
243
|
branch,
|
|
235
244
|
baseBranch: repo.baseBranch,
|
|
236
245
|
visibility: thread.isDM ? "private" : "org"
|
|
237
|
-
})
|
|
246
|
+
});
|
|
247
|
+
startedSessions.set(message, session.sessionId);
|
|
248
|
+
return memoryResourceId;
|
|
238
249
|
} catch (error) {
|
|
239
250
|
if (error instanceof ChannelSessionRejectedError || error instanceof SlackSessionStartError) throw error;
|
|
240
251
|
if (error instanceof FactorySourceControlConflictError) throw new SlackSessionStartError("Could not start a session: this Factory project has repositories from more than one source-control provider.", { cause: error });
|
|
@@ -245,22 +256,55 @@ function createChannelResourceIdResolver(deps) {
|
|
|
245
256
|
}
|
|
246
257
|
/**
|
|
247
258
|
* Thread id for a NEW Slack channel thread. Repo-backed threads take the
|
|
248
|
-
*
|
|
259
|
+
* session id AS their thread id, matching the web convention
|
|
249
260
|
* (FactoryStartCoordinator seeds threads with threadId = sessionId) so
|
|
250
261
|
* `/workspaces/{sessionId}/threads/{sessionId}` resolves Slack-created
|
|
251
|
-
* sessions exactly like web-created ones — no `?
|
|
262
|
+
* sessions exactly like web-created ones — no `?sessionId=` override needed.
|
|
252
263
|
* Chat-only threads keep the default random id: their `channel:...`
|
|
253
264
|
* resourceId is a memory key, not a unique thread id.
|
|
254
265
|
*/
|
|
255
|
-
|
|
266
|
+
function createChannelThreadIdResolver(startedSessions) {
|
|
267
|
+
return ({ message, defaultThreadId }) => startedSessions.get(message) ?? defaultThreadId;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* The Factory session a repo-backed Slack thread belongs to. A thread under
|
|
271
|
+
* the Factory resource is stamped with its session id (the startup migration
|
|
272
|
+
* stamps threads it moved there). An unmigrated thread runs under its session
|
|
273
|
+
* id as its resource, and a newer thread is named after its session. A stamp
|
|
274
|
+
* or thread id only counts under that session's memory resource; a thread
|
|
275
|
+
* named after a session it can't claim is refused. With no session row for
|
|
276
|
+
* either, the thread is addressed by its own id and fails authorization like
|
|
277
|
+
* any session without a row.
|
|
278
|
+
*/
|
|
279
|
+
const UNCLAIMED_SESSION = Symbol("unclaimed-session");
|
|
280
|
+
async function slackThreadSessionId(sessions, thread, loadThread, runs) {
|
|
281
|
+
if (thread.resourceId.startsWith("channel:")) return null;
|
|
282
|
+
const claims = async (sessionId) => {
|
|
283
|
+
const row = await sessions.getBySessionId(sessionId);
|
|
284
|
+
if (!row) return false;
|
|
285
|
+
if (sessionId !== thread.id && !sessionStampCounts(row, thread.resourceId)) return false;
|
|
286
|
+
const own = sessionId === thread.id ? thread : await loadThread(sessionId);
|
|
287
|
+
return thread.resourceId === memoryResourceOf(row, own, await isRunBound(row, runs));
|
|
288
|
+
};
|
|
289
|
+
const stamped = thread.metadata?.factorySessionId;
|
|
290
|
+
if (typeof stamped === "string" && stamped && await claims(stamped)) return stamped;
|
|
291
|
+
if (await sessions.getSourceControlBySessionId(thread.resourceId)) return thread.resourceId;
|
|
292
|
+
if (await claims(thread.id)) return thread.id;
|
|
293
|
+
if (await sessions.getBySessionId(thread.id)) return UNCLAIMED_SESSION;
|
|
294
|
+
return thread.id;
|
|
295
|
+
}
|
|
256
296
|
/** Create channel sessions with their Factory ownership present in initial controller state. */
|
|
257
297
|
function createChannelSessionResolver(deps) {
|
|
258
298
|
const sourceControlSessions = createSourceControlSessionLookup(configuredSourceControls(deps));
|
|
259
299
|
return async ({ controller, thread, requestContext }) => {
|
|
260
|
-
const
|
|
261
|
-
const
|
|
300
|
+
const stored = thread.metadata?.factorySessionId || thread.resourceId.startsWith("channel:") ? thread : await controller.queryThreadById({ threadId: thread.id }) ?? thread;
|
|
301
|
+
const resolved = await slackThreadSessionId(sourceControlSessions, stored, (threadId) => controller.queryThreadById({ threadId }), deps.workItems);
|
|
302
|
+
if (resolved === UNCLAIMED_SESSION) throw new Error(`Slack thread ${thread.id} is named after a Factory session it doesn't belong to.`);
|
|
303
|
+
const sessionId = resolved ?? thread.resourceId;
|
|
304
|
+
const sourceControl = sessionId.startsWith("channel:") ? null : await sourceControlSessions.getSourceControlBySessionId(sessionId);
|
|
305
|
+
const session = sourceControl ? await sourceControl.sessions.getBySessionId(sessionId) : null;
|
|
262
306
|
return controller.createSession({
|
|
263
|
-
id:
|
|
307
|
+
id: sessionId,
|
|
264
308
|
ownerId: controller.id,
|
|
265
309
|
resourceId: thread.resourceId,
|
|
266
310
|
threadId: thread.id,
|
|
@@ -299,15 +343,16 @@ function createChannelSessionStartHook(deps) {
|
|
|
299
343
|
await seedSessionOrg(session, readRequestContextOrgId(requestContext));
|
|
300
344
|
if (!projects) return;
|
|
301
345
|
if (thread.resourceId.startsWith("channel:")) return;
|
|
302
|
-
const
|
|
346
|
+
const sessionId = session.identity.getId();
|
|
347
|
+
const sourceControl = await sourceControlSessions.getSourceControlBySessionId(sessionId);
|
|
303
348
|
if (!sourceControl) return;
|
|
304
|
-
const sourceSession = await sourceControl.sessions.getBySessionId(
|
|
349
|
+
const sourceSession = await sourceControl.sessions.getBySessionId(sessionId);
|
|
305
350
|
if (!sourceSession?.factoryProjectId) return;
|
|
306
351
|
const threadId = session.thread.getId();
|
|
307
352
|
const binding = threadId && deps.workItems ? await deps.workItems.findRunBindingByThread({
|
|
308
353
|
orgId: sourceSession.orgId,
|
|
309
|
-
resourceId:
|
|
310
|
-
sessionId
|
|
354
|
+
resourceId: session.identity.getResourceId(),
|
|
355
|
+
sessionId,
|
|
311
356
|
threadId,
|
|
312
357
|
rejectAmbiguous: true
|
|
313
358
|
}) : null;
|
|
@@ -335,8 +380,13 @@ function createChannelSessionStartHook(deps) {
|
|
|
335
380
|
userId: owner.userId,
|
|
336
381
|
credentialScope: sessionModel.modelScope
|
|
337
382
|
});
|
|
338
|
-
const modeId = session.mode.get();
|
|
339
383
|
const activeThreadId = session.thread.getId();
|
|
384
|
+
if (activeThreadId) await session.thread.setSettingOn({
|
|
385
|
+
threadId: activeThreadId,
|
|
386
|
+
key: "factorySessionId",
|
|
387
|
+
value: sessionId
|
|
388
|
+
});
|
|
389
|
+
const modeId = session.mode.get();
|
|
340
390
|
if (await migratePersistedModelSelection({
|
|
341
391
|
getMetadata: async () => activeThreadId ? (await session.thread.getById({ threadId: activeThreadId }))?.metadata ?? {} : {},
|
|
342
392
|
modeId,
|
|
@@ -405,27 +455,28 @@ async function findInternalThread(mastra, thread) {
|
|
|
405
455
|
} },
|
|
406
456
|
perPage: 1
|
|
407
457
|
}) ?? { threads: [] };
|
|
408
|
-
return threads[0];
|
|
458
|
+
return threads[0] ?? null;
|
|
409
459
|
}
|
|
410
460
|
async function prepareExistingSessionOwnerContext(thread, deps, ctx, options) {
|
|
411
461
|
const sourceControls = configuredSourceControls(deps);
|
|
412
462
|
if (sourceControls.length === 0 && !options.requireInternalThread) return "ready";
|
|
413
|
-
const internalThread = await findInternalThread(ctx.mastra, thread);
|
|
463
|
+
const internalThread = options.internalThread !== void 0 ? options.internalThread : await findInternalThread(ctx.mastra, thread);
|
|
414
464
|
if (!internalThread) {
|
|
415
465
|
if (options.requireInternalThread) throw new Error(`Could not resolve the internal Slack thread for ${thread.id}.`);
|
|
416
466
|
return "ready";
|
|
417
467
|
}
|
|
418
468
|
if (sourceControls.length === 0 || internalThread.resourceId.startsWith("channel:")) return "ready";
|
|
419
469
|
const sessions = createSourceControlSessionLookup(sourceControls);
|
|
420
|
-
const
|
|
470
|
+
const memory = await ctx.mastra?.getStorage()?.getStore("memory");
|
|
471
|
+
const resolved = await slackThreadSessionId(sessions, internalThread, async (threadId) => memory?.getThreadById({ threadId }), deps.workItems);
|
|
472
|
+
if (resolved === UNCLAIMED_SESSION) return "access-denied";
|
|
473
|
+
const sessionId = resolved ?? internalThread.resourceId;
|
|
474
|
+
const sessionRow = await sessions.getBySessionId(sessionId);
|
|
421
475
|
if (sessionRow && sessionRow.orgId === options.expectedOrgId && sessionRow.visibility === "private" && sessionRow.userId !== options.senderUserId) return "access-denied";
|
|
422
|
-
if (!options.expectedOrgId) throw new Error(`Could not authorize the owner of Slack Factory session ${
|
|
423
|
-
const preparation = await prepareSessionRunContext(ctx.requestContext,
|
|
476
|
+
if (!options.expectedOrgId) throw new Error(`Could not authorize the owner of Slack Factory session ${sessionId}: the sender's account link has no organization.`);
|
|
477
|
+
const preparation = await prepareSessionRunContext(ctx.requestContext, sessionId, { sessions }, { expectedOrgId: options.expectedOrgId });
|
|
424
478
|
if (preparation === "organization-mismatch") return preparation;
|
|
425
|
-
if (preparation !== "prepared") {
|
|
426
|
-
const reason = preparation === "session-not-found" ? "no source-control session row exists for it, or its project repository row is missing" : "its source-control session row has no organization";
|
|
427
|
-
throw new Error(`Could not authorize the owner of Slack Factory session ${internalThread.resourceId}: ${reason}.`);
|
|
428
|
-
}
|
|
479
|
+
if (preparation !== "prepared") throw new Error(`Could not authorize the owner of Slack Factory session ${sessionId}: ${preparation === "session-not-found" ? "no source-control session row exists for it, or its project repository row is missing" : "its source-control session row has no organization"}.`);
|
|
429
480
|
return "ready";
|
|
430
481
|
}
|
|
431
482
|
/**
|
|
@@ -455,7 +506,8 @@ async function gateDispatch(thread, message, deps, ctx, options = { requireInter
|
|
|
455
506
|
const ownerContext = await prepareExistingSessionOwnerContext(thread, deps, ctx, {
|
|
456
507
|
expectedOrgId: sender.link.orgId,
|
|
457
508
|
senderUserId: sender.link.userId,
|
|
458
|
-
requireInternalThread: options.requireInternalThread
|
|
509
|
+
requireInternalThread: options.requireInternalThread,
|
|
510
|
+
internalThread: options.internalThread
|
|
459
511
|
});
|
|
460
512
|
if (ownerContext === "access-denied") {
|
|
461
513
|
await thread.post("This private Factory session belongs to another user.");
|
|
@@ -636,41 +688,90 @@ const createHandlers = (deps) => {
|
|
|
636
688
|
return {
|
|
637
689
|
onSubscribedMessage: async (thread, message, defaultHandler, ctx) => {
|
|
638
690
|
if (/^aside\b/i.test(message.text)) return ingestAside(thread, message, deps);
|
|
691
|
+
const internalThread = await findInternalThread(ctx.mastra, thread);
|
|
692
|
+
if (!message.isMention && internalThread?.metadata?.[MUTED_KEY] === "true") return;
|
|
639
693
|
try {
|
|
640
|
-
if (!await gateDispatch(thread, message, deps, ctx, {
|
|
694
|
+
if (!await gateDispatch(thread, message, deps, ctx, {
|
|
695
|
+
requireInternalThread: true,
|
|
696
|
+
internalThread
|
|
697
|
+
})) return;
|
|
641
698
|
} catch (error) {
|
|
642
699
|
await reportPreDispatchError(thread, message, ctx, error);
|
|
643
700
|
return;
|
|
644
701
|
}
|
|
702
|
+
const command = message.isMention ? muteCommand(message) : void 0;
|
|
703
|
+
if (command && internalThread) return setThreadMuted(thread, internalThread, message, ctx, command === "mute");
|
|
645
704
|
acknowledgeReceipt(thread, deps);
|
|
646
705
|
await defaultHandler(thread, message);
|
|
647
706
|
},
|
|
648
|
-
onMention:
|
|
707
|
+
onMention: async (thread, message, defaultHandler, ctx) => {
|
|
708
|
+
if (muteCommand(message)) return;
|
|
709
|
+
await newSessionChatHandler(thread, message, defaultHandler, ctx);
|
|
710
|
+
},
|
|
649
711
|
onDirectMessage: newSessionChatHandler
|
|
650
712
|
};
|
|
651
713
|
};
|
|
714
|
+
/** Thread metadata key; one Factory runs one Slack app, so this is per bot. */
|
|
715
|
+
const MUTED_KEY = "factory_muted";
|
|
716
|
+
/**
|
|
717
|
+
* `mute` or `unmute` when that word, with the mentions taken out, is the whole
|
|
718
|
+
* message. Reads Slack's raw text, where a mention is still `<@U…>`: the
|
|
719
|
+
* normalized `message.text` spells it as the bot's display name, which can
|
|
720
|
+
* hold spaces and punctuation (`@Mastra Factory(Caleb)`).
|
|
721
|
+
*/
|
|
722
|
+
function muteCommand(message) {
|
|
723
|
+
const raw = message.raw;
|
|
724
|
+
const rest = (typeof raw?.text === "string" ? raw.text : message.text).replace(/<@[^>]+>/g, " ").replace(/(?<!\w)@[\w.-]+/g, " ").trim().replace(/[.!]+$/, "").toLowerCase();
|
|
725
|
+
return rest === "mute" || rest === "unmute" ? rest : void 0;
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Stored on the Mastra thread next to `channel_subscribed`, so a mute holds
|
|
729
|
+
* across deploys and replicas. Callers run the sender's link and session
|
|
730
|
+
* access gate first. A reaction confirms it without posting.
|
|
731
|
+
*/
|
|
732
|
+
async function setThreadMuted(thread, internal, message, ctx, muted) {
|
|
733
|
+
const store = await ctx.mastra?.getStorage()?.getStore("memory");
|
|
734
|
+
if (!store) return;
|
|
735
|
+
await store.patchThread({
|
|
736
|
+
id: internal.id,
|
|
737
|
+
metadata: {
|
|
738
|
+
...internal.metadata,
|
|
739
|
+
[MUTED_KEY]: String(muted)
|
|
740
|
+
}
|
|
741
|
+
});
|
|
742
|
+
try {
|
|
743
|
+
await thread.adapter.addReaction(thread.id, message.id, muted ? "mute" : "loud_sound");
|
|
744
|
+
} catch (error) {
|
|
745
|
+
console.warn("[slack] mute reaction failed", {
|
|
746
|
+
thread: thread.id,
|
|
747
|
+
error
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
}
|
|
652
751
|
function createSlackChannelsConfig(deps) {
|
|
653
752
|
const adapter = createSlackAdapter({
|
|
654
753
|
...deps.slack,
|
|
655
754
|
webClientOptions: { timeout: SLACK_REQUEST_TIMEOUT_MS }
|
|
656
755
|
});
|
|
756
|
+
const slack = deps.adapterOptions?.streaming === false ? {
|
|
757
|
+
adapter,
|
|
758
|
+
...deps.adapterOptions
|
|
759
|
+
} : {
|
|
760
|
+
adapter,
|
|
761
|
+
...deps.adapterOptions,
|
|
762
|
+
streaming: deps.adapterOptions?.streaming ?? true
|
|
763
|
+
};
|
|
764
|
+
const startedSessions = /* @__PURE__ */ new WeakMap();
|
|
657
765
|
return {
|
|
658
|
-
adapters: { slack
|
|
659
|
-
adapter,
|
|
660
|
-
...deps.adapterOptions
|
|
661
|
-
} : {
|
|
662
|
-
adapter,
|
|
663
|
-
...deps.adapterOptions,
|
|
664
|
-
streaming: deps.adapterOptions?.streaming ?? true
|
|
665
|
-
} },
|
|
766
|
+
adapters: { slack },
|
|
666
767
|
handlers: createHandlers(deps),
|
|
667
|
-
resolveResourceId: createChannelResourceIdResolver(deps),
|
|
668
|
-
resolveThreadId:
|
|
768
|
+
resolveResourceId: createChannelResourceIdResolver(deps, startedSessions),
|
|
769
|
+
resolveThreadId: createChannelThreadIdResolver(startedSessions),
|
|
669
770
|
resolveSession: createChannelSessionResolver(deps),
|
|
670
771
|
onSessionStart: createChannelSessionStartHook(deps)
|
|
671
772
|
};
|
|
672
773
|
}
|
|
673
774
|
//#endregion
|
|
674
|
-
export { createChannelResourceIdResolver, createChannelSessionResolver, createChannelSessionStartHook, createHandlers, createSlackChannelsConfig,
|
|
775
|
+
export { createChannelResourceIdResolver, createChannelSessionResolver, createChannelSessionStartHook, createChannelThreadIdResolver, createHandlers, createSlackChannelsConfig, resolveFactoryForLink, resolveLinkedSender, slackThreadSource };
|
|
675
776
|
|
|
676
777
|
//# sourceMappingURL=slack.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"slack.js","names":[],"sources":["../../../src/integrations/slack/slack.ts"],"sourcesContent":["import { migratePersistedModelSelection } from '@mastra/core/agent-controller';\nimport { ChannelSessionRejectedError } from '@mastra/core/channels';\nimport type {\n ChannelHandler,\n ChannelHandlerContext,\n ChannelHandlers,\n ChannelSessionResolve,\n ChannelSessionStart,\n ResolveResourceId,\n ResolveThreadId,\n} from '@mastra/core/channels';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { createSlackAdapter } from '@mastra/slack';\nimport type { SlackAdapterChannelConfig } from '@mastra/slack';\nimport { Card, CardText, Actions, LinkButton } from 'chat';\n\nimport { FACTORY_INTERACTIVE_KEY } from '../../auth.js';\nimport {\n primeTenantCredentialsForRequestContext,\n primeTenantCredentialsForTenant,\n} from '../../routes/tenant-credentials.js';\nimport { markNewChannelSession } from '../../session/channel-session-link-processor.js';\nimport {\n createSourceControlSessionLookup,\n FactorySourceControlConflictError,\n hydrateFactorySession,\n resolveFactorySessionModel,\n resolveFactorySourceControl,\n resolvePrimaryEnvironmentRepository,\n} from '../../session/factory-session.js';\nimport { readRequestContextOrgId, seedSessionOrg } from '../../session/org-seed.js';\nimport type {\n ChannelAccountLink,\n ChannelAccountLinkKey,\n ChannelIdentityStorage,\n} from '../../storage/domains/channel-identity/base.js';\nimport type { FactoryActorExternalIdentity } from '../../storage/domains/comments/actor.js';\nimport { actorFromChannelAuthor } from '../../storage/domains/comments/actor.js';\nimport type { CommentsDomain } from '../../storage/domains/comments/domain.js';\nimport type { ModelDefaultsStorage } from '../../storage/domains/model-defaults/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';\nimport type { ExternalWorkItemSource, WorkItemRow, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport { FACTORY_SLACK_SENDER_KEY } from '../../tools/scope.js';\nimport type { FactoryChannelsConfig } from '../base.js';\nimport { prepareSessionRunContext } from '../subscription-session.js';\n\nimport { resolveEmojiShortcodes } from './emoji.js';\nimport { slackCommentSource } from './feed-publisher.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\nconst SLACK_REQUEST_TIMEOUT_MS = 15_000;\n\nclass SlackSessionStartError extends Error {}\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 a \"pick a default factory\"\n * card posted in the thread and no run. Unset → no factory routing (runs\n * dispatch as 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 /** Registered source-control partitions used to select the provider linked to each Factory project. */\n sourceControls?: readonly SourceControlStorageHandle[];\n /**\n * Model-defaults domain. When provided, a new repo-backed session starts on\n * the linked sender's default model before the factory's shared default. Read\n * once, when the thread's build model is first chosen; the choice is persisted\n * on the thread and never re-resolved. Unset → the factory default, as before.\n */\n modelDefaults?: ModelDefaultsStorage;\n /**\n * Factory work-items domain, used to find the card a Slack thread already\n * has so an `aside` can land on it. New threads never create cards.\n */\n workItems?: WorkItemsStorage;\n /**\n * Work-item feed. With it (and `workItems`), an `aside` lands as a comment on\n * the card the thread already has. Unset → asides stay ignored, as before.\n */\n feed?: Pick<CommentsDomain, 'createComment'>;\n /** Overrides applied to the Slack channel adapter entry. */\n adapterOptions?: SlackAdapterChannelConfig;\n}\n\nfunction configuredSourceControls(deps: SlackChannelDeps): readonly SourceControlStorageHandle[] {\n return deps.sourceControls ?? (deps.sourceControl ? [deps.sourceControl] : []);\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, thread), { fallbackToDM: true });\n }\n return { status: 'blocked' };\n}\n\nconst retryHint = (thread: HandlerThread) => (thread.isDM ? 'message me again' : 'mention me again');\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, thread: HandlerThread) {\n return Card({\n title: 'Connect your account',\n children: [\n CardText(`Connect your account to use this agent, then ${retryHint(thread)}.`),\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 };\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 — a \"pick a default factory\" card\n * posted publicly in the thread so Slack notifies the sender, and the run is\n * blocked.\n */\nexport async function resolveFactoryForLink({\n thread,\n link,\n key,\n accountLinks,\n projects,\n}: {\n thread: HandlerThread;\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 { status: 'resolved', factoryProjectId: existing.id };\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 { status: 'resolved', factoryProjectId: only.id };\n }\n\n const publicUrl = webPublicUrl();\n if (publicUrl) {\n await thread.post(\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 ${retryHint(thread)}.`\n : `Your account has several factories. Pick which one Slack sessions should go to, then ${retryHint(thread)}.`,\n ),\n Actions([\n LinkButton({\n url: `${publicUrl}/settings/connections`,\n label: 'Open settings',\n }),\n ]),\n ],\n }),\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 *\n * Top-level DM and channel conversations use the empty-threadTs thread form,\n * so the trailing segment can be empty; a bare `slack/` is not a valid git\n * ref. Fall back to the last non-empty segment (the channel id): one\n * deterministic branch per top-level conversation.\n */\nfunction threadBranch(threadId: string): string {\n const segments = threadId.split(':');\n const tail = segments.findLast(segment => segment.length > 0) ?? threadId;\n return `slack/${tail.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.\n *\n * A gated deployment refuses a thread it cannot place, rather than falling back\n * to a chat-only session: a repo-backed thread is the whole point of the\n * integration, and answering in a chat-only one would run the sender's request\n * in no project, on the SDK's built-in defaults. A linked sender whose project\n * cannot start a session gets an actionable error in Slack; the dispatch gate\n * handles unlinked or unrouted senders before this hook runs.\n * The hook only runs when a NEW thread is actually created (`getOrCreateThread`\n * resolves the owner lazily), so an established conversation is never touched:\n * it keeps its session, its model, and its history.\n *\n * The chat-only `channel:...` id survives for two cases where refusing would be\n * wrong: a deployment that cannot produce a repo-backed thread at all (no\n * account linking, no projects, or no source-control integration registered),\n * and a message carrying no sender id. In both, a `channel:` thread is the only\n * shape a session can take.\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 } = deps;\n const sourceControls = configuredSourceControls(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 // A deployment with no account linking, no projects, or no source-control\n // integration cannot produce a repo-backed thread at all, so a `channel:`\n // thread is the only shape it has. Every refusal below is a different thing\n // entirely: a sender the bot cannot place, in a deployment that can.\n if (!accountLinks || !projects || sourceControls.length === 0) return chatOnlyResourceId;\n // No sender id at all — a malformed message, not a sender the host turned\n // away. There is nothing to place, so give it the per-thread memory key.\n if (!message.author.userId) return chatOnlyResourceId;\n\n const externalTeamId = rawTeamId(message.raw);\n if (!externalTeamId) {\n throw new ChannelSessionRejectedError('No Slack workspace id on the message — the sender cannot be identified');\n }\n try {\n const link = await accountLinks.getAccountLink({\n platform,\n externalTeamId,\n externalUserId: message.author.userId,\n });\n if (!link) {\n throw new ChannelSessionRejectedError(\n `Slack sender ${message.author.userId} is not linked to a Factory account`,\n );\n }\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) {\n throw new ChannelSessionRejectedError(`Linked Slack sender ${message.author.userId} has no Factory project`);\n }\n\n // Linked and routed, so a repo-backed session is not a preference: with no\n // repository to work in there is no thread to start, and starting one\n // anyway would answer in a project the sender never picked, on the SDK's\n // built-in defaults.\n const sourceControl = await resolveFactorySourceControl({ sourceControls, orgId, factoryProjectId });\n if (!sourceControl) {\n const connections = await Promise.all(\n sourceControls.map(sourceControl => sourceControl.connections.list({ orgId, factoryProjectId })),\n );\n throw new SlackSessionStartError(\n connections.some(rows => rows.length > 0)\n ? 'Could not start a session: link a repository to this Factory project.'\n : 'Could not start a session: connect source control to this Factory project.',\n );\n }\n // The session's link is the factory's position-1 environment\n // repository (D1); the sandbox boots every environment repository.\n const repo = await resolvePrimaryEnvironmentRepository({ sourceControl, orgId, factoryProjectId });\n if (!repo.found) {\n throw new SlackSessionStartError(\n repo.reason === 'connection'\n ? 'Could not start a session: connect source control to this Factory project.'\n : 'Could not start a session: link a repository to this Factory project.',\n );\n }\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 // Keyed by factory, not by link: the thread's session stays found when the\n // position-1 repository changes between two messages.\n const existing = await sourceControl.sessions.getForBranch({\n factoryProjectId,\n userId: link.userId,\n branch,\n });\n if (existing) return existing.sessionId;\n const session = await sourceControl.sessions.create({\n sessionId: globalThis.crypto.randomUUID(),\n projectRepositoryId: repo.projectRepositoryId,\n factoryProjectId,\n orgId,\n userId: link.userId,\n branch,\n baseBranch: repo.baseBranch,\n // DMs are the only private origin; channel threads are org-visible.\n visibility: thread.isDM ? 'private' : 'org',\n });\n return session.sessionId;\n } catch (error) {\n if (error instanceof ChannelSessionRejectedError || error instanceof SlackSessionStartError) throw error;\n if (error instanceof FactorySourceControlConflictError) {\n throw new SlackSessionStartError(\n 'Could not start a session: this Factory project has repositories from more than one source-control provider.',\n { cause: error },\n );\n }\n console.error('[slack] failed to start repo-backed session for thread', thread.id, error);\n throw new SlackSessionStartError('Could not start a session right now. Please try again later.', {\n cause: error,\n });\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/** Create channel sessions with their Factory ownership present in initial controller state. */\nexport function createChannelSessionResolver(deps: SlackChannelDeps): ChannelSessionResolve {\n const sourceControlSessions = createSourceControlSessionLookup(configuredSourceControls(deps));\n return async ({ controller, thread, requestContext }) => {\n const sourceControl = thread.resourceId.startsWith('channel:')\n ? null\n : await sourceControlSessions.getSourceControlBySessionId(thread.resourceId);\n const session = sourceControl ? await sourceControl.sessions.getBySessionId(thread.resourceId) : null;\n return controller.createSession({\n id: thread.resourceId,\n ownerId: controller.id,\n resourceId: thread.resourceId,\n // Bind the Slack-created thread itself. Without it the scoped session\n // auto-selects (or creates) another thread and is switched onto this one later.\n threadId: thread.id,\n requestContext,\n ...(session?.factoryProjectId ? { tags: { factoryProjectId: session.factoryProjectId } } : {}),\n });\n };\n}\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 * The model this session starts on is picked here, once, from the project's\n * effective model scope for a session: the Factory default or the durable session owner's\n * default, else the SDK's built-in model. The choice is persisted on the thread\n * as `currentModelId`, so it outlives the process that made it.\n *\n * The model resolution is skipped on a session that already has a model\n * persisted on the thread. That is the durable record of a deliberate choice —\n * either an earlier start or a user's own switch — and re-applying a preference\n * over it would undo the user's selection every time the process restarts.\n */\nexport function createChannelSessionStartHook(deps: SlackChannelDeps): ChannelSessionStart {\n const { projects, modelDefaults } = deps;\n const sourceControlSessions = createSourceControlSessionLookup(configuredSourceControls(deps));\n return async ({ session, thread, requestContext }) => {\n // Seed the tenant org above every guard below. `gateDispatch` stamps it on\n // the message's request context before the session exists, so this needs no\n // storage read — which matters, because the model lookups below deliberately\n // skip storage on a restarted session. A channel-only thread and a thread\n // whose dispatch was ungated both land here with no org and are marked\n // unresolved rather than being left to look like a local session.\n await seedSessionOrg(session, readRequestContextOrgId(requestContext));\n\n if (!projects) return;\n if (thread.resourceId.startsWith('channel:')) return;\n\n const sourceControl = await sourceControlSessions.getSourceControlBySessionId(thread.resourceId);\n if (!sourceControl) return;\n const sourceSession = await sourceControl.sessions.getBySessionId(thread.resourceId);\n if (!sourceSession?.factoryProjectId) return;\n const threadId = session.thread.getId();\n const binding =\n threadId && deps.workItems\n ? await deps.workItems.findRunBindingByThread({\n orgId: sourceSession.orgId,\n resourceId: thread.resourceId,\n sessionId: thread.resourceId,\n threadId,\n rejectAmbiguous: true,\n })\n : null;\n const owner = {\n factoryProjectId: binding?.factoryProjectId ?? sourceSession.factoryProjectId,\n orgId: sourceSession.orgId,\n userId: sourceSession.userId,\n };\n\n const sessionModel = await resolveFactorySessionModel({\n projects,\n modelDefaults,\n factoryProjectId: owner.factoryProjectId,\n orgId: owner.orgId,\n ownerUserId: owner.userId,\n context: binding ? 'run' : 'session',\n });\n\n // Repo-backed Slack sessions use the source-control row's durable owner,\n // never the sender, for both model and credential scope.\n await session.state.set({\n factoryProjectId: owner.factoryProjectId,\n factoryModelScope: sessionModel.modelScope,\n factoryOwnerUserId: owner.userId,\n });\n // Route the org through the seed helper rather than stamping it directly:\n // an ungated dispatch marked this session unresolved above, and owner\n // recovery is the resolution that has to clear that marker with it.\n await seedSessionOrg(session, owner.orgId);\n await primeTenantCredentialsForTenant({\n orgId: owner.orgId,\n userId: owner.userId,\n credentialScope: sessionModel.modelScope,\n });\n\n const modeId = session.mode.get();\n const activeThreadId = session.thread.getId();\n const persistedModelId = await migratePersistedModelSelection({\n getMetadata: async () =>\n activeThreadId\n ? (((await session.thread.getById({ threadId: activeThreadId }))?.metadata as\n Record<string, unknown> | undefined) ?? {})\n : {},\n modeId,\n set: (key: string, value: unknown) =>\n activeThreadId ? session.thread.setSettingOn({ threadId: activeThreadId, key, value }) : Promise.resolve(),\n threadId: activeThreadId ?? undefined,\n });\n if (persistedModelId) {\n // Subagent models live in session state only, so restore the ones this\n // thread pinned at its first start instead of re-resolving them.\n for (const agentType of SUBAGENT_TYPES) {\n const modelId = await session.thread.getSetting({ key: pinnedSubagentModelKey(agentType) });\n if (typeof modelId === 'string') await applySubagentModel(session, agentType, modelId);\n }\n } else {\n // `hydrateFactorySession` persists the scoped model, a connected provider's\n // provider default, or the SDK mode default as this thread's model of record.\n const selectedModelId =\n (await hydrateFactorySession(session, {\n orgId: owner.orgId,\n modelScope: sessionModel.modelScope,\n ownerUserId: owner.userId,\n defaultModelId: sessionModel.modelId,\n })) ?? session.model.get();\n\n // Pin subagent models on the thread like the main model so a restart\n // restores the selected scope's choice rather than re-resolving it.\n for (const agentType of SUBAGENT_TYPES) {\n if (!selectedModelId) continue;\n if (await applySubagentModel(session, agentType, selectedModelId)) {\n await session.thread.setSetting({ key: pinnedSubagentModelKey(agentType), value: selectedModelId });\n }\n }\n }\n };\n}\n\nconst SUBAGENT_TYPES = ['explore', 'plan', 'execute'] as const;\nconst pinnedSubagentModelKey = (agentType: string) => `slackSubagentModelId_${agentType}`;\n\n/** Best-effort: a subagent model that can't be applied must not fail the message. */\nasync function applySubagentModel(\n session: Parameters<ChannelSessionStart>[0]['session'],\n agentType: (typeof SUBAGENT_TYPES)[number],\n modelId: string,\n): Promise<boolean> {\n try {\n await session.subagents.model.set({ modelId, agentType });\n return true;\n } catch (error) {\n console.warn('[slack] Failed to apply the subagent model', {\n agentType,\n modelId,\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\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\nasync function prepareExistingSessionOwnerContext(\n thread: HandlerThread,\n deps: SlackChannelDeps,\n ctx: ChannelHandlerContext,\n options: { expectedOrgId?: string; senderUserId?: string; requireInternalThread: boolean },\n): Promise<'ready' | 'organization-mismatch' | 'access-denied'> {\n const sourceControls = configuredSourceControls(deps);\n if (sourceControls.length === 0 && !options.requireInternalThread) return 'ready';\n\n const internalThread = await findInternalThread(ctx.mastra, thread);\n if (!internalThread) {\n if (options.requireInternalThread) {\n throw new Error(`Could not resolve the internal Slack thread for ${thread.id}.`);\n }\n return 'ready';\n }\n if (sourceControls.length === 0 || internalThread.resourceId.startsWith('channel:')) return 'ready';\n const sessions = createSourceControlSessionLookup(sourceControls);\n const sessionRow = await sessions.getBySessionId(internalThread.resourceId);\n if (\n sessionRow &&\n sessionRow.orgId === options.expectedOrgId &&\n sessionRow.visibility === 'private' &&\n sessionRow.userId !== options.senderUserId\n ) {\n return 'access-denied';\n }\n if (!options.expectedOrgId) {\n throw new Error(\n `Could not authorize the owner of Slack Factory session ${internalThread.resourceId}: the sender's account link has no organization.`,\n );\n }\n\n const preparation = await prepareSessionRunContext(\n ctx.requestContext,\n internalThread.resourceId,\n { sessions },\n { expectedOrgId: options.expectedOrgId },\n );\n if (preparation === 'organization-mismatch') return preparation;\n if (preparation !== 'prepared') {\n const reason =\n preparation === 'session-not-found'\n ? 'no source-control session row exists for it, or its project repository row is missing'\n : 'its source-control session row has no organization';\n throw new Error(`Could not authorize the owner of Slack Factory session ${internalThread.resourceId}: ${reason}.`);\n }\n return 'ready';\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 deps: SlackChannelDeps,\n ctx: ChannelHandlerContext,\n options: { requireInternalThread: boolean } = { requireInternalThread: false },\n): Promise<{\n routed?: { link: ChannelAccountLink; factoryProjectId: string };\n} | null> {\n const { accountLinks, projects } = deps;\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 const ownerContext = await prepareExistingSessionOwnerContext(thread, deps, ctx, {\n expectedOrgId: sender.link.orgId,\n senderUserId: sender.link.userId,\n requireInternalThread: options.requireInternalThread,\n });\n if (ownerContext === 'access-denied') {\n await thread.post('This private Factory session belongs to another user.');\n return null;\n }\n if (ownerContext === 'organization-mismatch') {\n await thread.post('This thread belongs to a Factory session in another organization.');\n return null;\n }\n // Credential resolution reads an in-memory snapshot that only priming\n // fills, so prime whichever tenant now owns the run (the sender, or the\n // existing session's owner) — otherwise a cold snapshot after a restart\n // fails the run until that user happens to hit the web UI.\n await primeTenantCredentialsForRequestContext(ctx.requestContext);\n\n const route = await resolveFactoryForLink({ thread, ...sender, accountLinks, projects });\n if (route.status === 'blocked') return null;\n if (route.status === 'resolved') {\n // The model runs with the session owner's credentials, but Factory tools\n // must act as the authenticated Slack sender, not the session owner.\n if (sender.link.orgId) {\n ctx.requestContext.set(FACTORY_SLACK_SENDER_KEY, { userId: sender.link.userId, orgId: sender.link.orgId });\n ctx.requestContext.set(FACTORY_INTERACTIVE_KEY, true);\n }\n return { routed: { link: sender.link, factoryProjectId: route.factoryProjectId } };\n }\n }\n return {};\n}\n\n/**\n * A channel id and a `ts` name a thread only inside the workspace that issued\n * them, so the team scopes the card's key — without it two workspaces could\n * hold one key and an aside would land on another tenant's card.\n */\nexport function slackThreadSource(thread: HandlerThread, teamId?: string): ExternalWorkItemSource {\n return {\n integrationId: thread.adapter.name,\n type: 'slack-thread',\n ...(teamId ? { workspaceId: teamId } : {}),\n externalId: thread.id,\n };\n}\n\n/** Cards written before the key carried a team are still keyed bare. */\nasync function findThreadWorkItem(\n workItems: WorkItemsStorage,\n thread: HandlerThread,\n teamId?: string,\n): Promise<WorkItemRow | null> {\n const scoped = await workItems.getBySource(slackThreadSource(thread, teamId));\n if (scoped || !teamId) return scoped;\n return workItems.getBySource(slackThreadSource(thread));\n}\n\nfunction preDispatchErrorDetails(error: unknown): { message: string; cause?: { message: string } } {\n const readMessage = (value: unknown) => {\n const message =\n typeof value === 'string'\n ? value\n : value && typeof value === 'object' && 'message' in value\n ? value.message\n : undefined;\n return typeof message === 'string' && message.length > 0 ? message : undefined;\n };\n try {\n const message = readMessage(error) ?? 'Unknown error';\n const cause = error && typeof error === 'object' && 'cause' in error ? readMessage(error.cause) : undefined;\n return { message, ...(cause ? { cause: { message: cause } } : {}) };\n } catch {\n return { message: 'Error details unavailable' };\n }\n}\n\nasync function reportPreDispatchError(\n thread: HandlerThread,\n message: HandlerMessage,\n ctx: ChannelHandlerContext,\n error: unknown,\n): Promise<void> {\n try {\n if (error instanceof ChannelSessionRejectedError) return;\n } catch {\n // A thrown proxy can fail even the refusal check; still report the failure.\n }\n const correlation = {\n platform: thread.adapter.name,\n threadId: thread.id,\n messageId: message.id,\n authorId: message.author.userId,\n };\n const logger = typeof ctx.mastra?.getLogger === 'function' ? ctx.mastra.getLogger() : undefined;\n const logError = (line: string) => (logger ? logger.error(line) : console.error(line));\n logError(`[slack] Pre-dispatch failure ${JSON.stringify({ ...correlation, error: preDispatchErrorDetails(error) })}`);\n try {\n // The message id is the lookup key for the diagnostic above.\n await thread.post(`Couldn’t start processing your message. Please try again.\\n\\`messageId: ${message.id}\\``);\n } catch (deliveryError) {\n logError(\n `[slack] Failed to deliver pre-dispatch error reply ${JSON.stringify({ ...correlation, error: preDispatchErrorDetails(deliveryError) })}`,\n );\n }\n}\n\n/**\n * What the sender sees while nothing has been posted yet. Core's typing\n * wrapper only sets a status once the agent stream yields its first chunk,\n * and everything before that — credential priming, session rows, the\n * controller start hook, model time-to-first-token — is silent. Pin the same\n * status Factory's `typingStatus` uses for reasoning so the bot visibly\n * \"picks up\" as soon as the gate passes, and the stream's own status replaces\n * it without a visual change. Slack clears it on the first post; core clears\n * it when a run ends without posting.\n */\nconst EARLY_TYPING_STATUS = 'is thinking...';\n\nfunction acknowledgeReceipt(thread: HandlerThread, deps: SlackChannelDeps): void {\n if (deps.adapterOptions?.typingStatus === false) return;\n // Best-effort like every other status call: a failed status must not\n // keep the run from starting.\n void thread.startTyping(EARLY_TYPING_STATUS).catch(error => {\n console.warn('[slack] early typing status failed', { thread: thread.id, error });\n });\n}\n\nfunction createNewSessionChatHandler(deps: SlackChannelDeps): ChannelHandler {\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 try {\n if (!(await gateDispatch(thread, message, deps, ctx))) return;\n // A mention on a not-yet-subscribed thread is a NEW session. The default\n // handler auto-subscribes, so once subscribed this is a follow-up — the\n // thread already carries its link. Factory posts nothing of its own:\n // FactoryChannelSessionLinkProcessor emits the `Open session ↗` link right\n // after the agent's first reply.\n if (!(await thread.isSubscribed())) markNewChannelSession(ctx.requestContext);\n acknowledgeReceipt(thread, deps);\n } catch (error) {\n await reportPreDispatchError(thread, message, ctx, error);\n return;\n }\n await defaultHandler(thread, message);\n };\n}\n\n/**\n * An `aside` never reaches the agent, but it is still part of the conversation:\n * record it on the card the thread already has. The link is resolved here rather\n * than through `gateDispatch`, which posts a Connect card an aside must not\n * trigger. Best-effort — nothing here may surface in the Slack thread.\n */\nasync function ingestAside(\n thread: HandlerThread,\n message: HandlerMessage,\n { feed, workItems, accountLinks }: SlackChannelDeps,\n): Promise<void> {\n if (!feed || !workItems) return;\n const body = resolveEmojiShortcodes(message.text.replace(/^aside\\b[,:]?\\s*/i, '').trim());\n if (!body) return;\n try {\n const teamId = slackTeamId(message);\n const workItem = await findThreadWorkItem(workItems, thread, teamId);\n if (!workItem) return;\n\n const external: FactoryActorExternalIdentity = {\n platform: thread.adapter.name,\n ...(teamId ? { teamId } : {}),\n messageId: message.id,\n userId: message.author.userId,\n userName: message.author.userName,\n fullName: message.author.fullName,\n isBot: message.author.isBot,\n };\n const link =\n accountLinks && teamId\n ? await accountLinks.getAccountLink({\n platform: external.platform,\n externalTeamId: teamId,\n externalUserId: external.userId,\n })\n : null;\n\n const result = await feed.createComment({\n orgId: workItem.orgId,\n workItemId: workItem.id,\n author: actorFromChannelAuthor(external, link),\n body,\n occurredAt: message.metadata.dateSent,\n externalSource: slackCommentSource(thread.id, message.id, teamId),\n });\n if (result.status !== 'created') {\n console.warn('[slack] aside not ingested', { thread: thread.id, messageTs: message.id, status: result.status });\n }\n } catch (error) {\n // Slack was acked before this handler ran, so a lost aside is never redelivered.\n console.warn('[slack] aside ingest failed', { thread: thread.id, messageTs: message.id, error });\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 ingestAside(thread, message, deps);\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 try {\n const gate = await gateDispatch(thread, message, deps, ctx, { requireInternalThread: true });\n if (!gate) return;\n } catch (error) {\n await reportPreDispatchError(thread, message, ctx, error);\n return;\n }\n acknowledgeReceipt(thread, deps);\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 // Per HTTP attempt, not per call: the WebClient's own retry policy still\n // waits out a 429. Without it a dead socket hangs a post forever.\n const adapter = createSlackAdapter({ ...deps.slack, webClientOptions: { timeout: SLACK_REQUEST_TIMEOUT_MS } });\n const slack =\n deps.adapterOptions?.streaming === false\n ? { adapter, ...deps.adapterOptions }\n : { adapter, ...deps.adapterOptions, streaming: deps.adapterOptions?.streaming ?? true };\n\n return {\n adapters: { slack },\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 resolveSession: createChannelSessionResolver(deps),\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":";;;;;;;;;;;;;;;AA0DA,MAAM,2BAA2B;AAEjC,IAAM,yBAAN,cAAqC,MAAM,CAAC;AAwD5C,SAAS,yBAAyB,MAA+D;CAC/F,OAAO,KAAK,mBAAmB,KAAK,gBAAgB,CAAC,KAAK,aAAa,IAAI,CAAC;AAC9E;;;;;;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,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,CA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I;CAE9D,OAAO;EACL,qBAAqB,OAAO,QAAQ,SAAS,gBAAgB,QAAQ;GAInE,IAAI,YAAY,KAAK,QAAQ,IAAI,GAAG,OAAO,YAAY,QAAQ,SAAS,IAAI;GAK5E,IAAI;IAEF,IAAI,CAAC,MADc,aAAa,QAAQ,SAAS,MAAM,KAAK,EAAE,uBAAuB,KAAK,CAAC,GAChF;GACb,SAAS,OAAO;IACd,MAAM,uBAAuB,QAAQ,SAAS,KAAK,KAAK;IACxD;GACF;GACA,mBAAmB,QAAQ,IAAI;GAC/B,MAAM,eAAe,QAAQ,OAAO;EACtC;EACA,WAAW;EACX,iBAAiB;CACnB;AACF;AAUA,SAAgB,0BAA0B,MAA6E;CAGrH,MAAM,UAAU,mBAAmB;EAAE,GAAG,KAAK;EAAO,kBAAkB,EAAE,SAAS,yBAAyB;CAAE,CAAC;CAM7G,OAAO;EACL,UAAU,EAAE,OALZ,KAAK,gBAAgB,cAAc,QAC/B;GAAE;GAAS,GAAG,KAAK;EAAe,IAClC;GAAE;GAAS,GAAG,KAAK;GAAgB,WAAW,KAAK,gBAAgB,aAAa;EAAK,EAGvE;EAClB,UAAU,eAAe,IAAI;EAG7B,mBAAmB,gCAAgC,IAAI;EACvD,iBAAiB;EACjB,gBAAgB,6BAA6B,IAAI;EAGjD,gBAAgB,8BAA8B,IAAI;CACpD;AACF"}
|
|
1
|
+
{"version":3,"file":"slack.js","names":[],"sources":["../../../src/integrations/slack/slack.ts"],"sourcesContent":["import { migratePersistedModelSelection } from '@mastra/core/agent-controller';\nimport { ChannelSessionRejectedError } from '@mastra/core/channels';\nimport type {\n ChannelHandler,\n ChannelHandlerContext,\n ChannelHandlers,\n ChannelSessionResolve,\n ChannelSessionStart,\n ResolveResourceId,\n ResolveThreadId,\n} from '@mastra/core/channels';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { createSlackAdapter } from '@mastra/slack';\nimport type { SlackAdapterChannelConfig } from '@mastra/slack';\nimport { Card, CardText, Actions, LinkButton } from 'chat';\n\nimport { FACTORY_INTERACTIVE_KEY } from '../../auth.js';\nimport {\n primeTenantCredentialsForRequestContext,\n primeTenantCredentialsForTenant,\n} from '../../routes/tenant-credentials.js';\nimport {\n createSourceControlSessionLookup,\n FactorySourceControlConflictError,\n hydrateFactorySession,\n resolveFactorySessionModel,\n resolveFactorySourceControl,\n resolvePrimaryEnvironmentRepository,\n} from '../../session/factory-session.js';\nimport { readRequestContextOrgId, seedSessionOrg } from '../../session/org-seed.js';\nimport { isRunBound, memoryResourceOf, sessionStampCounts } from '../../session/session-threads.js';\nimport type { SessionRunBindings } from '../../session/session-threads.js';\nimport type {\n ChannelAccountLink,\n ChannelAccountLinkKey,\n ChannelIdentityStorage,\n} from '../../storage/domains/channel-identity/base.js';\nimport type { FactoryActorExternalIdentity } from '../../storage/domains/comments/actor.js';\nimport { actorFromChannelAuthor } from '../../storage/domains/comments/actor.js';\nimport type { CommentsDomain } from '../../storage/domains/comments/domain.js';\nimport type { ModelDefaultsStorage } from '../../storage/domains/model-defaults/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';\nimport type { ExternalWorkItemSource, WorkItemRow, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport { FACTORY_SLACK_SENDER_KEY } from '../../tools/scope.js';\nimport type { FactoryChannelsConfig } from '../base.js';\nimport { prepareSessionRunContext } from '../subscription-session.js';\nimport { markNewChannelSession } from './channel-session-link-processor.js';\n\nimport { resolveEmojiShortcodes } from './emoji.js';\nimport { slackCommentSource } from './feed-publisher.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\nconst SLACK_REQUEST_TIMEOUT_MS = 15_000;\n\nclass SlackSessionStartError extends Error {}\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 a \"pick a default factory\"\n * card posted in the thread and no run. Unset → no factory routing (runs\n * dispatch as 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 /** Registered source-control partitions used to select the provider linked to each Factory project. */\n sourceControls?: readonly SourceControlStorageHandle[];\n /**\n * Model-defaults domain. When provided, a new repo-backed session starts on\n * the linked sender's default model before the factory's shared default. Read\n * once, when the thread's build model is first chosen; the choice is persisted\n * on the thread and never re-resolved. Unset → the factory default, as before.\n */\n modelDefaults?: ModelDefaultsStorage;\n /**\n * Factory work-items domain, used to find the card a Slack thread already\n * has so an `aside` can land on it. New threads never create cards.\n */\n workItems?: WorkItemsStorage;\n /**\n * Work-item feed. With it (and `workItems`), an `aside` lands as a comment on\n * the card the thread already has. Unset → asides stay ignored, as before.\n */\n feed?: Pick<CommentsDomain, 'createComment'>;\n /** Overrides applied to the Slack channel adapter entry. */\n adapterOptions?: SlackAdapterChannelConfig;\n}\n\nfunction configuredSourceControls(deps: SlackChannelDeps): readonly SourceControlStorageHandle[] {\n return deps.sourceControls ?? (deps.sourceControl ? [deps.sourceControl] : []);\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, thread), { fallbackToDM: true });\n }\n return { status: 'blocked' };\n}\n\nconst retryHint = (thread: HandlerThread) => (thread.isDM ? 'message me again' : 'mention me again');\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, thread: HandlerThread) {\n return Card({\n title: 'Connect your account',\n children: [\n CardText(`Connect your account to use this agent, then ${retryHint(thread)}.`),\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 };\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 — a \"pick a default factory\" card\n * posted publicly in the thread so Slack notifies the sender, and the run is\n * blocked.\n */\nexport async function resolveFactoryForLink({\n thread,\n link,\n key,\n accountLinks,\n projects,\n}: {\n thread: HandlerThread;\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 { status: 'resolved', factoryProjectId: existing.id };\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 { status: 'resolved', factoryProjectId: only.id };\n }\n\n const publicUrl = webPublicUrl();\n if (publicUrl) {\n await thread.post(\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 ${retryHint(thread)}.`\n : `Your account has several factories. Pick which one Slack sessions should go to, then ${retryHint(thread)}.`,\n ),\n Actions([\n LinkButton({\n url: `${publicUrl}/settings/connections`,\n label: 'Open settings',\n }),\n ]),\n ],\n }),\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 *\n * Top-level DM and channel conversations use the empty-threadTs thread form,\n * so the trailing segment can be empty; a bare `slack/` is not a valid git\n * ref. Fall back to the last non-empty segment (the channel id): one\n * deterministic branch per top-level conversation.\n */\nfunction threadBranch(threadId: string): string {\n const segments = threadId.split(':');\n const tail = segments.findLast(segment => segment.length > 0) ?? threadId;\n return `slack/${tail.replace(/[^A-Za-z0-9_/-]/g, '-')}`;\n}\n\n/**\n * Session ids of repo-backed Slack threads, keyed by the message that started\n * them. The resourceId resolver records the session it found or created; the\n * thread-id resolver, which core runs next for the same message, names the new\n * thread after it.\n */\nexport type SlackStartedSessions = WeakMap<object, string>;\n\n/**\n * Resolve the resourceId for a NEW Slack channel thread. A linked sender whose\n * factory has a repository gets a Factory session. A channel thread belongs to\n * the Factory: its resourceId is the Factory id, so the thread shares the\n * Factory's memory. A DM is private to the sender, so it runs under the\n * sender's user id and shares memory with their own sessions. The session id is recorded in `startedSessions` for the\n * thread-id resolver. 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.\n *\n * A gated deployment refuses a thread it cannot place, rather than falling back\n * to a chat-only session: a repo-backed thread is the whole point of the\n * integration, and answering in a chat-only one would run the sender's request\n * in no project, on the SDK's built-in defaults. A linked sender whose project\n * cannot start a session gets an actionable error in Slack; the dispatch gate\n * handles unlinked or unrouted senders before this hook runs.\n * The hook only runs when a NEW thread is actually created (`getOrCreateThread`\n * resolves the owner lazily), so an established conversation is never touched:\n * it keeps its session, its model, and its history.\n *\n * The chat-only `channel:...` id survives for two cases where refusing would be\n * wrong: a deployment that cannot produce a repo-backed thread at all (no\n * account linking, no projects, or no source-control integration registered),\n * and a message carrying no sender id. In both, a `channel:` thread is the only\n * shape a session can take.\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(\n deps: SlackChannelDeps,\n startedSessions: SlackStartedSessions = new WeakMap(),\n): ResolveResourceId {\n const { accountLinks, projects } = deps;\n const sourceControls = configuredSourceControls(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 // A deployment with no account linking, no projects, or no source-control\n // integration cannot produce a repo-backed thread at all, so a `channel:`\n // thread is the only shape it has. Every refusal below is a different thing\n // entirely: a sender the bot cannot place, in a deployment that can.\n if (!accountLinks || !projects || sourceControls.length === 0) return chatOnlyResourceId;\n // No sender id at all — a malformed message, not a sender the host turned\n // away. There is nothing to place, so give it the per-thread memory key.\n if (!message.author.userId) return chatOnlyResourceId;\n\n const externalTeamId = rawTeamId(message.raw);\n if (!externalTeamId) {\n throw new ChannelSessionRejectedError('No Slack workspace id on the message — the sender cannot be identified');\n }\n try {\n const link = await accountLinks.getAccountLink({\n platform,\n externalTeamId,\n externalUserId: message.author.userId,\n });\n if (!link) {\n throw new ChannelSessionRejectedError(\n `Slack sender ${message.author.userId} is not linked to a Factory account`,\n );\n }\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) {\n throw new ChannelSessionRejectedError(`Linked Slack sender ${message.author.userId} has no Factory project`);\n }\n\n // Linked and routed, so a repo-backed session is not a preference: with no\n // repository to work in there is no thread to start, and starting one\n // anyway would answer in a project the sender never picked, on the SDK's\n // built-in defaults.\n const sourceControl = await resolveFactorySourceControl({ sourceControls, orgId, factoryProjectId });\n if (!sourceControl) {\n const connections = await Promise.all(\n sourceControls.map(sourceControl => sourceControl.connections.list({ orgId, factoryProjectId })),\n );\n throw new SlackSessionStartError(\n connections.some(rows => rows.length > 0)\n ? 'Could not start a session: link a repository to this Factory project.'\n : 'Could not start a session: connect source control to this Factory project.',\n );\n }\n // The session's link is the factory's position-1 environment\n // repository (D1); the sandbox boots every environment repository.\n const repo = await resolvePrimaryEnvironmentRepository({ sourceControl, orgId, factoryProjectId });\n if (!repo.found) {\n throw new SlackSessionStartError(\n repo.reason === 'connection'\n ? 'Could not start a session: connect source control to this Factory project.'\n : 'Could not start a session: link a repository to this Factory project.',\n );\n }\n\n const branch = threadBranch(thread.id);\n const memoryResourceId = thread.isDM ? link.userId : factoryProjectId;\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 // Keyed by factory, not by link: the thread's session stays found when the\n // position-1 repository changes between two messages.\n const existing = await sourceControl.sessions.getForBranch({\n factoryProjectId,\n userId: link.userId,\n branch,\n });\n if (existing) {\n startedSessions.set(message, existing.sessionId);\n return memoryResourceId;\n }\n const session = await sourceControl.sessions.create({\n sessionId: globalThis.crypto.randomUUID(),\n projectRepositoryId: repo.projectRepositoryId,\n factoryProjectId,\n orgId,\n userId: link.userId,\n branch,\n baseBranch: repo.baseBranch,\n // DMs are the only private origin; channel threads are org-visible.\n visibility: thread.isDM ? 'private' : 'org',\n });\n startedSessions.set(message, session.sessionId);\n return memoryResourceId;\n } catch (error) {\n if (error instanceof ChannelSessionRejectedError || error instanceof SlackSessionStartError) throw error;\n if (error instanceof FactorySourceControlConflictError) {\n throw new SlackSessionStartError(\n 'Could not start a session: this Factory project has repositories from more than one source-control provider.',\n { cause: error },\n );\n }\n console.error('[slack] failed to start repo-backed session for thread', thread.id, error);\n throw new SlackSessionStartError('Could not start a session right now. Please try again later.', {\n cause: error,\n });\n }\n };\n}\n\n/**\n * Thread id for a NEW Slack channel thread. Repo-backed threads take the\n * 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 `?sessionId=` 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 function createChannelThreadIdResolver(startedSessions: SlackStartedSessions): ResolveThreadId {\n return ({ message, defaultThreadId }) => startedSessions.get(message) ?? defaultThreadId;\n}\n\n/**\n * The Factory session a repo-backed Slack thread belongs to. A thread under\n * the Factory resource is stamped with its session id (the startup migration\n * stamps threads it moved there). An unmigrated thread runs under its session\n * id as its resource, and a newer thread is named after its session. A stamp\n * or thread id only counts under that session's memory resource; a thread\n * named after a session it can't claim is refused. With no session row for\n * either, the thread is addressed by its own id and fails authorization like\n * any session without a row.\n */\nconst UNCLAIMED_SESSION = Symbol('unclaimed-session');\n\nasync function slackThreadSessionId(\n sessions: ReturnType<typeof createSourceControlSessionLookup>,\n thread: { id: string; resourceId: string; metadata?: Record<string, unknown> },\n loadThread: (threadId: string) => Promise<{ resourceId: string } | null | undefined>,\n runs: SessionRunBindings | undefined,\n): Promise<string | null | typeof UNCLAIMED_SESSION> {\n if (thread.resourceId.startsWith('channel:')) return null;\n // Stamps and thread ids are client-writable: a session only claims a thread\n // under its own memory resource.\n const claims = async (sessionId: string) => {\n const row = await sessions.getBySessionId(sessionId);\n if (!row) return false;\n // A stamp only counts where the session's stamps are trusted.\n if (sessionId !== thread.id && !sessionStampCounts(row, thread.resourceId)) return false;\n const own = sessionId === thread.id ? thread : await loadThread(sessionId);\n return thread.resourceId === memoryResourceOf(row, own, await isRunBound(row, runs));\n };\n const stamped = thread.metadata?.factorySessionId;\n if (typeof stamped === 'string' && stamped && (await claims(stamped))) return stamped;\n if (await sessions.getSourceControlBySessionId(thread.resourceId)) return thread.resourceId;\n if (await claims(thread.id)) return thread.id;\n if (await sessions.getBySessionId(thread.id)) return UNCLAIMED_SESSION;\n // With no session row the thread is its own session: falling back to the\n // resource would put every such thread under the Factory (or a sender) into\n // one shared session.\n return thread.id;\n}\n\n/** Create channel sessions with their Factory ownership present in initial controller state. */\nexport function createChannelSessionResolver(deps: SlackChannelDeps): ChannelSessionResolve {\n const sourceControlSessions = createSourceControlSessionLookup(configuredSourceControls(deps));\n return async ({ controller, thread, requestContext }) => {\n // A session-bound Slack thread is addressed by its Factory session id and\n // runs under the thread's resource (the Factory). A chat-only thread is its\n // own session, addressed by its `channel:` resource.\n // Approval clicks pass the thread without its metadata; load the stored\n // thread whenever the session stamp is missing so a migrated thread's\n // stamp is read.\n const stamped = (thread as { metadata?: Record<string, unknown> }).metadata?.factorySessionId;\n const stored =\n stamped || thread.resourceId.startsWith('channel:')\n ? thread\n : ((await controller.queryThreadById({ threadId: thread.id })) ?? thread);\n const resolved = await slackThreadSessionId(\n sourceControlSessions,\n stored,\n threadId => controller.queryThreadById({ threadId }),\n deps.workItems,\n );\n if (resolved === UNCLAIMED_SESSION) {\n throw new Error(`Slack thread ${thread.id} is named after a Factory session it doesn't belong to.`);\n }\n const sessionId = resolved ?? thread.resourceId;\n const sourceControl = sessionId.startsWith('channel:')\n ? null\n : await sourceControlSessions.getSourceControlBySessionId(sessionId);\n const session = sourceControl ? await sourceControl.sessions.getBySessionId(sessionId) : null;\n return controller.createSession({\n id: sessionId,\n ownerId: controller.id,\n resourceId: thread.resourceId,\n // Bind the Slack-created thread itself. Without it the session\n // auto-selects (or creates) another thread and is switched onto this one later.\n threadId: thread.id,\n requestContext,\n ...(session?.factoryProjectId ? { tags: { factoryProjectId: session.factoryProjectId } } : {}),\n });\n };\n}\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 * The model this session starts on is picked here, once, from the project's\n * effective model scope for a session: the Factory default or the durable session owner's\n * default, else the SDK's built-in model. The choice is persisted on the thread\n * as `currentModelId`, so it outlives the process that made it.\n *\n * The model resolution is skipped on a session that already has a model\n * persisted on the thread. That is the durable record of a deliberate choice —\n * either an earlier start or a user's own switch — and re-applying a preference\n * over it would undo the user's selection every time the process restarts.\n */\nexport function createChannelSessionStartHook(deps: SlackChannelDeps): ChannelSessionStart {\n const { projects, modelDefaults } = deps;\n const sourceControlSessions = createSourceControlSessionLookup(configuredSourceControls(deps));\n return async ({ session, thread, requestContext }) => {\n // Seed the tenant org above every guard below. `gateDispatch` stamps it on\n // the message's request context before the session exists, so this needs no\n // storage read — which matters, because the model lookups below deliberately\n // skip storage on a restarted session. A channel-only thread and a thread\n // whose dispatch was ungated both land here with no org and are marked\n // unresolved rather than being left to look like a local session.\n await seedSessionOrg(session, readRequestContextOrgId(requestContext));\n\n if (!projects) return;\n if (thread.resourceId.startsWith('channel:')) return;\n\n const sessionId = session.identity.getId();\n const sourceControl = await sourceControlSessions.getSourceControlBySessionId(sessionId);\n if (!sourceControl) return;\n const sourceSession = await sourceControl.sessions.getBySessionId(sessionId);\n if (!sourceSession?.factoryProjectId) return;\n const threadId = session.thread.getId();\n const binding =\n threadId && deps.workItems\n ? await deps.workItems.findRunBindingByThread({\n orgId: sourceSession.orgId,\n resourceId: session.identity.getResourceId(),\n sessionId,\n threadId,\n rejectAmbiguous: true,\n })\n : null;\n const owner = {\n factoryProjectId: binding?.factoryProjectId ?? sourceSession.factoryProjectId,\n orgId: sourceSession.orgId,\n userId: sourceSession.userId,\n };\n\n const sessionModel = await resolveFactorySessionModel({\n projects,\n modelDefaults,\n factoryProjectId: owner.factoryProjectId,\n orgId: owner.orgId,\n ownerUserId: owner.userId,\n context: binding ? 'run' : 'session',\n });\n\n // Repo-backed Slack sessions use the source-control row's durable owner,\n // never the sender, for both model and credential scope.\n await session.state.set({\n factoryProjectId: owner.factoryProjectId,\n factoryModelScope: sessionModel.modelScope,\n factoryOwnerUserId: owner.userId,\n });\n // Route the org through the seed helper rather than stamping it directly:\n // an ungated dispatch marked this session unresolved above, and owner\n // recovery is the resolution that has to clear that marker with it.\n await seedSessionOrg(session, owner.orgId);\n await primeTenantCredentialsForTenant({\n orgId: owner.orgId,\n userId: owner.userId,\n credentialScope: sessionModel.modelScope,\n });\n\n const activeThreadId = session.thread.getId();\n // Threads of one Factory share its resource; the stamp ties this thread to its session.\n if (activeThreadId) {\n await session.thread.setSettingOn({ threadId: activeThreadId, key: 'factorySessionId', value: sessionId });\n }\n const modeId = session.mode.get();\n const persistedModelId = await migratePersistedModelSelection({\n getMetadata: async () =>\n activeThreadId\n ? (((await session.thread.getById({ threadId: activeThreadId }))?.metadata as\n Record<string, unknown> | undefined) ?? {})\n : {},\n modeId,\n set: (key: string, value: unknown) =>\n activeThreadId ? session.thread.setSettingOn({ threadId: activeThreadId, key, value }) : Promise.resolve(),\n threadId: activeThreadId ?? undefined,\n });\n if (persistedModelId) {\n // Subagent models live in session state only, so restore the ones this\n // thread pinned at its first start instead of re-resolving them.\n for (const agentType of SUBAGENT_TYPES) {\n const modelId = await session.thread.getSetting({ key: pinnedSubagentModelKey(agentType) });\n if (typeof modelId === 'string') await applySubagentModel(session, agentType, modelId);\n }\n } else {\n // `hydrateFactorySession` persists the scoped model, a connected provider's\n // provider default, or the SDK mode default as this thread's model of record.\n const selectedModelId =\n (await hydrateFactorySession(session, {\n orgId: owner.orgId,\n modelScope: sessionModel.modelScope,\n ownerUserId: owner.userId,\n defaultModelId: sessionModel.modelId,\n })) ?? session.model.get();\n\n // Pin subagent models on the thread like the main model so a restart\n // restores the selected scope's choice rather than re-resolving it.\n for (const agentType of SUBAGENT_TYPES) {\n if (!selectedModelId) continue;\n if (await applySubagentModel(session, agentType, selectedModelId)) {\n await session.thread.setSetting({ key: pinnedSubagentModelKey(agentType), value: selectedModelId });\n }\n }\n }\n };\n}\n\nconst SUBAGENT_TYPES = ['explore', 'plan', 'execute'] as const;\nconst pinnedSubagentModelKey = (agentType: string) => `slackSubagentModelId_${agentType}`;\n\n/** Best-effort: a subagent model that can't be applied must not fail the message. */\nasync function applySubagentModel(\n session: Parameters<ChannelSessionStart>[0]['session'],\n agentType: (typeof SUBAGENT_TYPES)[number],\n modelId: string,\n): Promise<boolean> {\n try {\n await session.subagents.model.set({ modelId, agentType });\n return true;\n } catch (error) {\n console.warn('[slack] Failed to apply the subagent model', {\n agentType,\n modelId,\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\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] ?? null;\n}\n\ntype InternalThread = Awaited<ReturnType<typeof findInternalThread>>;\n\nasync function prepareExistingSessionOwnerContext(\n thread: HandlerThread,\n deps: SlackChannelDeps,\n ctx: ChannelHandlerContext,\n options: {\n expectedOrgId?: string;\n senderUserId?: string;\n requireInternalThread: boolean;\n /** Already looked up by the caller; `null` means it doesn't exist. */\n internalThread?: InternalThread;\n },\n): Promise<'ready' | 'organization-mismatch' | 'access-denied'> {\n const sourceControls = configuredSourceControls(deps);\n if (sourceControls.length === 0 && !options.requireInternalThread) return 'ready';\n\n const internalThread =\n options.internalThread !== undefined ? options.internalThread : await findInternalThread(ctx.mastra, thread);\n if (!internalThread) {\n if (options.requireInternalThread) {\n throw new Error(`Could not resolve the internal Slack thread for ${thread.id}.`);\n }\n return 'ready';\n }\n if (sourceControls.length === 0 || internalThread.resourceId.startsWith('channel:')) return 'ready';\n const sessions = createSourceControlSessionLookup(sourceControls);\n const memory = await ctx.mastra?.getStorage()?.getStore('memory');\n const resolved = await slackThreadSessionId(\n sessions,\n internalThread,\n async threadId => memory?.getThreadById({ threadId }),\n deps.workItems,\n );\n if (resolved === UNCLAIMED_SESSION) return 'access-denied';\n const sessionId = resolved ?? internalThread.resourceId;\n const sessionRow = await sessions.getBySessionId(sessionId);\n if (\n sessionRow &&\n sessionRow.orgId === options.expectedOrgId &&\n sessionRow.visibility === 'private' &&\n sessionRow.userId !== options.senderUserId\n ) {\n return 'access-denied';\n }\n if (!options.expectedOrgId) {\n throw new Error(\n `Could not authorize the owner of Slack Factory session ${sessionId}: the sender's account link has no organization.`,\n );\n }\n\n const preparation = await prepareSessionRunContext(\n ctx.requestContext,\n sessionId,\n { sessions },\n { expectedOrgId: options.expectedOrgId },\n );\n if (preparation === 'organization-mismatch') return preparation;\n if (preparation !== 'prepared') {\n const reason =\n preparation === 'session-not-found'\n ? 'no source-control session row exists for it, or its project repository row is missing'\n : 'its source-control session row has no organization';\n throw new Error(`Could not authorize the owner of Slack Factory session ${sessionId}: ${reason}.`);\n }\n return 'ready';\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 deps: SlackChannelDeps,\n ctx: ChannelHandlerContext,\n options: { requireInternalThread: boolean; internalThread?: InternalThread } = { requireInternalThread: false },\n): Promise<{\n routed?: { link: ChannelAccountLink; factoryProjectId: string };\n} | null> {\n const { accountLinks, projects } = deps;\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 const ownerContext = await prepareExistingSessionOwnerContext(thread, deps, ctx, {\n expectedOrgId: sender.link.orgId,\n senderUserId: sender.link.userId,\n requireInternalThread: options.requireInternalThread,\n internalThread: options.internalThread,\n });\n if (ownerContext === 'access-denied') {\n await thread.post('This private Factory session belongs to another user.');\n return null;\n }\n if (ownerContext === 'organization-mismatch') {\n await thread.post('This thread belongs to a Factory session in another organization.');\n return null;\n }\n // Credential resolution reads an in-memory snapshot that only priming\n // fills, so prime whichever tenant now owns the run (the sender, or the\n // existing session's owner) — otherwise a cold snapshot after a restart\n // fails the run until that user happens to hit the web UI.\n await primeTenantCredentialsForRequestContext(ctx.requestContext);\n\n const route = await resolveFactoryForLink({ thread, ...sender, accountLinks, projects });\n if (route.status === 'blocked') return null;\n if (route.status === 'resolved') {\n // The model runs with the session owner's credentials, but Factory tools\n // must act as the authenticated Slack sender, not the session owner.\n if (sender.link.orgId) {\n ctx.requestContext.set(FACTORY_SLACK_SENDER_KEY, { userId: sender.link.userId, orgId: sender.link.orgId });\n ctx.requestContext.set(FACTORY_INTERACTIVE_KEY, true);\n }\n return { routed: { link: sender.link, factoryProjectId: route.factoryProjectId } };\n }\n }\n return {};\n}\n\n/**\n * A channel id and a `ts` name a thread only inside the workspace that issued\n * them, so the team scopes the card's key — without it two workspaces could\n * hold one key and an aside would land on another tenant's card.\n */\nexport function slackThreadSource(thread: HandlerThread, teamId?: string): ExternalWorkItemSource {\n return {\n integrationId: thread.adapter.name,\n type: 'slack-thread',\n ...(teamId ? { workspaceId: teamId } : {}),\n externalId: thread.id,\n };\n}\n\n/** Cards written before the key carried a team are still keyed bare. */\nasync function findThreadWorkItem(\n workItems: WorkItemsStorage,\n thread: HandlerThread,\n teamId?: string,\n): Promise<WorkItemRow | null> {\n const scoped = await workItems.getBySource(slackThreadSource(thread, teamId));\n if (scoped || !teamId) return scoped;\n return workItems.getBySource(slackThreadSource(thread));\n}\n\nfunction preDispatchErrorDetails(error: unknown): { message: string; cause?: { message: string } } {\n const readMessage = (value: unknown) => {\n const message =\n typeof value === 'string'\n ? value\n : value && typeof value === 'object' && 'message' in value\n ? value.message\n : undefined;\n return typeof message === 'string' && message.length > 0 ? message : undefined;\n };\n try {\n const message = readMessage(error) ?? 'Unknown error';\n const cause = error && typeof error === 'object' && 'cause' in error ? readMessage(error.cause) : undefined;\n return { message, ...(cause ? { cause: { message: cause } } : {}) };\n } catch {\n return { message: 'Error details unavailable' };\n }\n}\n\nasync function reportPreDispatchError(\n thread: HandlerThread,\n message: HandlerMessage,\n ctx: ChannelHandlerContext,\n error: unknown,\n): Promise<void> {\n try {\n if (error instanceof ChannelSessionRejectedError) return;\n } catch {\n // A thrown proxy can fail even the refusal check; still report the failure.\n }\n const correlation = {\n platform: thread.adapter.name,\n threadId: thread.id,\n messageId: message.id,\n authorId: message.author.userId,\n };\n const logger = typeof ctx.mastra?.getLogger === 'function' ? ctx.mastra.getLogger() : undefined;\n const logError = (line: string) => (logger ? logger.error(line) : console.error(line));\n logError(`[slack] Pre-dispatch failure ${JSON.stringify({ ...correlation, error: preDispatchErrorDetails(error) })}`);\n try {\n // The message id is the lookup key for the diagnostic above.\n await thread.post(`Couldn’t start processing your message. Please try again.\\n\\`messageId: ${message.id}\\``);\n } catch (deliveryError) {\n logError(\n `[slack] Failed to deliver pre-dispatch error reply ${JSON.stringify({ ...correlation, error: preDispatchErrorDetails(deliveryError) })}`,\n );\n }\n}\n\n/**\n * What the sender sees while nothing has been posted yet. Core's typing\n * wrapper only sets a status once the agent stream yields its first chunk,\n * and everything before that — credential priming, session rows, the\n * controller start hook, model time-to-first-token — is silent. Pin the same\n * status Factory's `typingStatus` uses for reasoning so the bot visibly\n * \"picks up\" as soon as the gate passes, and the stream's own status replaces\n * it without a visual change. Slack clears it on the first post; core clears\n * it when a run ends without posting.\n */\nconst EARLY_TYPING_STATUS = 'is thinking...';\n\nfunction acknowledgeReceipt(thread: HandlerThread, deps: SlackChannelDeps): void {\n if (deps.adapterOptions?.typingStatus === false) return;\n // Best-effort like every other status call: a failed status must not\n // keep the run from starting.\n void thread.startTyping(EARLY_TYPING_STATUS).catch(error => {\n console.warn('[slack] early typing status failed', { thread: thread.id, error });\n });\n}\n\nfunction createNewSessionChatHandler(deps: SlackChannelDeps): ChannelHandler {\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 try {\n if (!(await gateDispatch(thread, message, deps, ctx))) return;\n // A mention on a not-yet-subscribed thread is a NEW session. The default\n // handler auto-subscribes, so once subscribed this is a follow-up — the\n // thread already carries its link. Factory posts nothing of its own:\n // FactoryChannelSessionLinkProcessor emits the `Open session ↗` link right\n // after the agent's first reply.\n if (!(await thread.isSubscribed())) markNewChannelSession(ctx.requestContext);\n acknowledgeReceipt(thread, deps);\n } catch (error) {\n await reportPreDispatchError(thread, message, ctx, error);\n return;\n }\n await defaultHandler(thread, message);\n };\n}\n\n/**\n * An `aside` never reaches the agent, but it is still part of the conversation:\n * record it on the card the thread already has. The link is resolved here rather\n * than through `gateDispatch`, which posts a Connect card an aside must not\n * trigger. Best-effort — nothing here may surface in the Slack thread.\n */\nasync function ingestAside(\n thread: HandlerThread,\n message: HandlerMessage,\n { feed, workItems, accountLinks }: SlackChannelDeps,\n): Promise<void> {\n if (!feed || !workItems) return;\n const body = resolveEmojiShortcodes(message.text.replace(/^aside\\b[,:]?\\s*/i, '').trim());\n if (!body) return;\n try {\n const teamId = slackTeamId(message);\n const workItem = await findThreadWorkItem(workItems, thread, teamId);\n if (!workItem) return;\n\n const external: FactoryActorExternalIdentity = {\n platform: thread.adapter.name,\n ...(teamId ? { teamId } : {}),\n messageId: message.id,\n userId: message.author.userId,\n userName: message.author.userName,\n fullName: message.author.fullName,\n isBot: message.author.isBot,\n };\n const link =\n accountLinks && teamId\n ? await accountLinks.getAccountLink({\n platform: external.platform,\n externalTeamId: teamId,\n externalUserId: external.userId,\n })\n : null;\n\n const result = await feed.createComment({\n orgId: workItem.orgId,\n workItemId: workItem.id,\n author: actorFromChannelAuthor(external, link),\n body,\n occurredAt: message.metadata.dateSent,\n externalSource: slackCommentSource(thread.id, message.id, teamId),\n });\n if (result.status !== 'created') {\n console.warn('[slack] aside not ingested', { thread: thread.id, messageTs: message.id, status: result.status });\n }\n } catch (error) {\n // Slack was acked before this handler ran, so a lost aside is never redelivered.\n console.warn('[slack] aside ingest failed', { thread: thread.id, messageTs: message.id, error });\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 ingestAside(thread, message, deps);\n // Looked up once here for the mute check and the access gate below.\n const internalThread = await findInternalThread(ctx.mastra, thread);\n // A muted thread ignores everything that doesn't tag the bot, and the\n // skipped messages never reach the session.\n if (!message.isMention && internalThread?.metadata?.[MUTED_KEY] === 'true') 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). Mute and unmute pass the same gate, so only\n // someone allowed to prompt this session can change what it listens to.\n try {\n const gate = await gateDispatch(thread, message, deps, ctx, { requireInternalThread: true, internalThread });\n if (!gate) return;\n } catch (error) {\n await reportPreDispatchError(thread, message, ctx, error);\n return;\n }\n const command = message.isMention ? muteCommand(message) : undefined;\n if (command && internalThread) return setThreadMuted(thread, internalThread, message, ctx, command === 'mute');\n acknowledgeReceipt(thread, deps);\n await defaultHandler(thread, message);\n },\n onMention: async (thread, message, defaultHandler, ctx) => {\n // `@bot mute` in a thread the bot never joined has nothing to mute, and\n // must not start a session about the word \"mute\".\n if (muteCommand(message)) return;\n await newSessionChatHandler(thread, message, defaultHandler, ctx);\n },\n onDirectMessage: newSessionChatHandler,\n };\n};\n\n/** Thread metadata key; one Factory runs one Slack app, so this is per bot. */\nconst MUTED_KEY = 'factory_muted';\n\n/**\n * `mute` or `unmute` when that word, with the mentions taken out, is the whole\n * message. Reads Slack's raw text, where a mention is still `<@U…>`: the\n * normalized `message.text` spells it as the bot's display name, which can\n * hold spaces and punctuation (`@Mastra Factory(Caleb)`).\n */\nfunction muteCommand(message: HandlerMessage): 'mute' | 'unmute' | undefined {\n const raw = message.raw as { text?: unknown } | undefined;\n const text = typeof raw?.text === 'string' ? raw.text : message.text;\n const rest = text\n .replace(/<@[^>]+>/g, ' ')\n .replace(/(?<!\\w)@[\\w.-]+/g, ' ')\n .trim()\n .replace(/[.!]+$/, '')\n .toLowerCase();\n return rest === 'mute' || rest === 'unmute' ? rest : undefined;\n}\n\n/**\n * Stored on the Mastra thread next to `channel_subscribed`, so a mute holds\n * across deploys and replicas. Callers run the sender's link and session\n * access gate first. A reaction confirms it without posting.\n */\nasync function setThreadMuted(\n thread: HandlerThread,\n internal: NonNullable<InternalThread>,\n message: HandlerMessage,\n ctx: ChannelHandlerContext,\n muted: boolean,\n): Promise<void> {\n const store = await ctx.mastra?.getStorage()?.getStore('memory');\n if (!store) return;\n await store.patchThread({ id: internal.id, metadata: { ...internal.metadata, [MUTED_KEY]: String(muted) } });\n try {\n await thread.adapter.addReaction(thread.id, message.id, muted ? 'mute' : 'loud_sound');\n } catch (error) {\n console.warn('[slack] mute reaction failed', { thread: thread.id, error });\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 // Per HTTP attempt, not per call: the WebClient's own retry policy still\n // waits out a 429. Without it a dead socket hangs a post forever.\n const adapter = createSlackAdapter({ ...deps.slack, webClientOptions: { timeout: SLACK_REQUEST_TIMEOUT_MS } });\n const slack =\n deps.adapterOptions?.streaming === false\n ? { adapter, ...deps.adapterOptions }\n : { adapter, ...deps.adapterOptions, streaming: deps.adapterOptions?.streaming ?? true };\n\n const startedSessions: SlackStartedSessions = new WeakMap();\n return {\n adapters: { slack },\n handlers: createHandlers(deps),\n // New linked+repo-backed threads belong to the Factory and are named after\n // the Factory session they start, which makes the controller session repo-backed.\n resolveResourceId: createChannelResourceIdResolver(deps, startedSessions),\n resolveThreadId: createChannelThreadIdResolver(startedSessions),\n resolveSession: createChannelSessionResolver(deps),\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":";;;;;;;;;;;;;;;;AA4DA,MAAM,2BAA2B;AAEjC,IAAM,yBAAN,cAAqC,MAAM,CAAC;AAwD5C,SAAS,yBAAyB,MAA+D;CAC/F,OAAO,KAAK,mBAAmB,KAAK,gBAAgB,CAAC,KAAK,aAAa,IAAI,CAAC;AAC9E;;;;;;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,SAAS,UAAU;EAC5C,MAAM,KAAM,IAAI,KAA0B;EAC1C,IAAI,OAAO,OAAO,YAAY,IAAI,OAAO;CAC3C;AAEF;;;;;AA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