@agentforge-ai/channels-slack 0.7.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/LICENSE ADDED
@@ -0,0 +1,197 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!)
184
+
185
+ Copyright [yyyy] [name of copyright owner]
186
+
187
+ Licensed under the Apache License, Version 2.0 (the "License");
188
+ you may not use this file except in compliance with the License.
189
+ You may obtain a copy of the License at
190
+
191
+ http://www.apache.org/licenses/LICENSE-2.0
192
+
193
+ Unless required by applicable law or agreed to in writing, software
194
+ distributed under the License is distributed on an "AS IS" BASIS,
195
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
196
+ See the License for the specific language governing permissions and
197
+ limitations under the License.
@@ -0,0 +1,240 @@
1
+ import { ChannelAdapter, ChannelConfig, OutboundMessage, SendResult, ChannelCapabilities, HealthStatus } from '@agentforge-ai/core';
2
+ import { z } from 'zod';
3
+
4
+ declare const slackConfigSchema: z.ZodObject<{
5
+ botToken: z.ZodString;
6
+ appToken: z.ZodString;
7
+ signingSecret: z.ZodString;
8
+ socketMode: z.ZodDefault<z.ZodBoolean>;
9
+ port: z.ZodDefault<z.ZodNumber>;
10
+ }, "strip", z.ZodTypeAny, {
11
+ botToken: string;
12
+ appToken: string;
13
+ signingSecret: string;
14
+ socketMode: boolean;
15
+ port: number;
16
+ }, {
17
+ botToken: string;
18
+ appToken: string;
19
+ signingSecret: string;
20
+ socketMode?: boolean | undefined;
21
+ port?: number | undefined;
22
+ }>;
23
+ type SlackConfig = z.infer<typeof slackConfigSchema>;
24
+ interface SlackMessage {
25
+ type: string;
26
+ subtype?: string;
27
+ channel: string;
28
+ user: string;
29
+ text: string;
30
+ ts: string;
31
+ thread_ts?: string;
32
+ bot_id?: string;
33
+ blocks?: SlackBlock[];
34
+ files?: SlackFile[];
35
+ }
36
+ interface SlackFile {
37
+ id: string;
38
+ name: string;
39
+ mimetype: string;
40
+ url_private: string;
41
+ size: number;
42
+ }
43
+ interface SlackEvent {
44
+ type: string;
45
+ event_ts: string;
46
+ user?: string;
47
+ channel?: string;
48
+ text?: string;
49
+ ts?: string;
50
+ thread_ts?: string;
51
+ bot_id?: string;
52
+ subtype?: string;
53
+ command?: string;
54
+ }
55
+ type SlackBlock = SlackSectionBlock | SlackDividerBlock | SlackActionsBlock | SlackHeaderBlock | SlackContextBlock | SlackImageBlock;
56
+ interface SlackSectionBlock {
57
+ type: 'section';
58
+ text?: SlackTextObject;
59
+ fields?: SlackTextObject[];
60
+ accessory?: SlackBlockElement;
61
+ block_id?: string;
62
+ }
63
+ interface SlackDividerBlock {
64
+ type: 'divider';
65
+ block_id?: string;
66
+ }
67
+ interface SlackActionsBlock {
68
+ type: 'actions';
69
+ elements: SlackBlockElement[];
70
+ block_id?: string;
71
+ }
72
+ interface SlackHeaderBlock {
73
+ type: 'header';
74
+ text: SlackTextObject;
75
+ block_id?: string;
76
+ }
77
+ interface SlackContextBlock {
78
+ type: 'context';
79
+ elements: (SlackTextObject | SlackImageElement)[];
80
+ block_id?: string;
81
+ }
82
+ interface SlackImageBlock {
83
+ type: 'image';
84
+ image_url: string;
85
+ alt_text: string;
86
+ title?: SlackTextObject;
87
+ block_id?: string;
88
+ }
89
+ interface SlackTextObject {
90
+ type: 'plain_text' | 'mrkdwn';
91
+ text: string;
92
+ emoji?: boolean;
93
+ }
94
+ type SlackBlockElement = SlackButtonElement | SlackImageElement | SlackOverflowElement;
95
+ interface SlackButtonElement {
96
+ type: 'button';
97
+ text: SlackTextObject;
98
+ action_id: string;
99
+ value?: string;
100
+ url?: string;
101
+ style?: 'primary' | 'danger';
102
+ }
103
+ interface SlackImageElement {
104
+ type: 'image';
105
+ image_url: string;
106
+ alt_text: string;
107
+ }
108
+ interface SlackOverflowElement {
109
+ type: 'overflow';
110
+ action_id: string;
111
+ options: Array<{
112
+ text: SlackTextObject;
113
+ value: string;
114
+ }>;
115
+ }
116
+
117
+ /**
118
+ * Slack Channel Adapter for AgentForge.
119
+ *
120
+ * Implements the ChannelAdapter interface using Slack Bolt.js with
121
+ * Socket Mode and Events API support.
122
+ *
123
+ * Features:
124
+ * - Socket Mode (WebSocket) and HTTP Events API
125
+ * - Block Kit rich messages
126
+ * - Slash command handling
127
+ * - app_mention event handling
128
+ * - Signature verification (HMAC-SHA256 via crypto.subtle)
129
+ * - Rate limiting with queue and delay
130
+ * - Zod config validation
131
+ *
132
+ * @packageDocumentation
133
+ */
134
+
135
+ declare class SlackAdapter extends ChannelAdapter {
136
+ readonly platform = "slack";
137
+ private app;
138
+ private slackConfig;
139
+ private messageTimestamps;
140
+ private readonly rateLimitPerSecond;
141
+ private sendQueue;
142
+ private processingQueue;
143
+ private mentionHandler;
144
+ private slashCommandHandlers;
145
+ connect(config: ChannelConfig): Promise<void>;
146
+ disconnect(): Promise<void>;
147
+ sendMessage(message: OutboundMessage): Promise<SendResult>;
148
+ /**
149
+ * Send a message with Block Kit blocks.
150
+ */
151
+ sendBlocks(channelId: string, blocks: SlackBlock[], text?: string): Promise<SendResult>;
152
+ deleteMessage(platformMessageId: string, chatId: string): Promise<boolean>;
153
+ getCapabilities(): ChannelCapabilities;
154
+ healthCheck(): Promise<{
155
+ status: HealthStatus;
156
+ details?: string;
157
+ }>;
158
+ editMessage(platformMessageId: string, message: Partial<OutboundMessage>): Promise<SendResult>;
159
+ addReaction(platformMessageId: string, chatId: string, emoji: string): Promise<boolean>;
160
+ onSlashCommand(command: string, handler: (payload: {
161
+ channel_id: string;
162
+ user_id: string;
163
+ text: string;
164
+ trigger_id: string;
165
+ }) => void | Promise<void>): void;
166
+ onMention(handler: (event: {
167
+ channel: string;
168
+ user: string;
169
+ text: string;
170
+ ts: string;
171
+ thread_ts?: string;
172
+ }) => void | Promise<void>): void;
173
+ /**
174
+ * Verify Slack request signature using HMAC-SHA256 via crypto.subtle.
175
+ * Used for HTTP Events API mode (not needed for Socket Mode).
176
+ */
177
+ static verifySignature(signingSecret: string, body: string, timestamp: string, signature: string): Promise<boolean>;
178
+ private enforceRateLimit;
179
+ private enqueueRateLimited;
180
+ private processQueue;
181
+ private getChatType;
182
+ }
183
+
184
+ /**
185
+ * Slack Channel for AgentForge.
186
+ *
187
+ * Bridges the SlackAdapter with the AgentForge Convex chat pipeline.
188
+ * This module:
189
+ * - Starts the Slack bot (Socket Mode or Events API)
190
+ * - Routes incoming messages through the agent execution pipeline
191
+ * - Creates/reuses Convex threads per Slack channel+user
192
+ * - Stores all messages in the Convex messages table
193
+ * - Sends agent responses back to the Slack user
194
+ *
195
+ * @packageDocumentation
196
+ */
197
+
198
+ interface SlackChannelConfig {
199
+ /** Slack Bot Token (xoxb-...) */
200
+ botToken: string;
201
+ /** Slack App-Level Token (xapp-...) for Socket Mode */
202
+ appToken: string;
203
+ /** Slack Signing Secret */
204
+ signingSecret: string;
205
+ /** Agent ID to route messages to */
206
+ agentId: string;
207
+ /** Convex deployment URL */
208
+ convexUrl: string;
209
+ /** Whether to use Socket Mode (default: true) */
210
+ socketMode?: boolean;
211
+ /** HTTP port for Events API mode (default: 3002) */
212
+ port?: number;
213
+ /** User ID for Convex operations (default: 'slack') */
214
+ userId?: string;
215
+ /** Log level: 'debug' | 'info' | 'warn' | 'error' (default: 'info') */
216
+ logLevel?: 'debug' | 'info' | 'warn' | 'error';
217
+ }
218
+ declare class SlackChannel {
219
+ private adapter;
220
+ private convex;
221
+ private config;
222
+ private threadMap;
223
+ private logger;
224
+ private processingMessages;
225
+ private isRunning;
226
+ constructor(config: SlackChannelConfig);
227
+ start(): Promise<void>;
228
+ stop(): Promise<void>;
229
+ getThreadMap(): ReadonlyMap<string, string>;
230
+ getAdapter(): SlackAdapter;
231
+ get running(): boolean;
232
+ private handleEvent;
233
+ private handleInboundMessage;
234
+ private routeToAgent;
235
+ private getOrCreateThread;
236
+ private splitMessage;
237
+ }
238
+ declare function startSlackChannel(overrides?: Partial<SlackChannelConfig>): Promise<SlackChannel>;
239
+
240
+ export { type SlackActionsBlock, SlackAdapter, type SlackBlock, type SlackBlockElement, type SlackButtonElement, SlackChannel, type SlackConfig, type SlackContextBlock, type SlackDividerBlock, type SlackEvent, type SlackFile, type SlackHeaderBlock, type SlackImageBlock, type SlackImageElement, type SlackMessage, type SlackOverflowElement, type SlackSectionBlock, type SlackTextObject, slackConfigSchema, startSlackChannel };
package/dist/index.js ADDED
@@ -0,0 +1,694 @@
1
+ // src/slack-adapter.ts
2
+ import { App } from "@slack/bolt";
3
+ import {
4
+ ChannelAdapter,
5
+ MessageNormalizer
6
+ } from "@agentforge-ai/core";
7
+
8
+ // src/types.ts
9
+ import { z } from "zod";
10
+ var slackConfigSchema = z.object({
11
+ botToken: z.string().min(1, "Bot token is required").startsWith("xoxb-", "Bot token must start with xoxb-"),
12
+ appToken: z.string().min(1, "App token is required").startsWith("xapp-", "App token must start with xapp-"),
13
+ signingSecret: z.string().min(1, "Signing secret is required"),
14
+ socketMode: z.boolean().default(true),
15
+ port: z.number().int().min(1).max(65535).default(3002)
16
+ });
17
+
18
+ // src/slack-adapter.ts
19
+ var SlackAdapter = class extends ChannelAdapter {
20
+ platform = "slack";
21
+ app = null;
22
+ slackConfig = null;
23
+ // Rate limiting
24
+ messageTimestamps = [];
25
+ rateLimitPerSecond = 50;
26
+ // Slack tier 3 limit
27
+ sendQueue = [];
28
+ processingQueue = false;
29
+ // Event handlers registered by consumers
30
+ mentionHandler = null;
31
+ slashCommandHandlers = /* @__PURE__ */ new Map();
32
+ // ----- Lifecycle -----
33
+ async connect(config) {
34
+ const parsed = slackConfigSchema.safeParse({
35
+ botToken: config.credentials.botToken,
36
+ appToken: config.credentials.appToken,
37
+ signingSecret: config.credentials.signingSecret,
38
+ socketMode: config.settings?.socketMode ?? true,
39
+ port: config.settings?.port ?? 3002
40
+ });
41
+ if (!parsed.success) {
42
+ const issues = parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
43
+ throw new Error(`Invalid Slack config: ${issues}`);
44
+ }
45
+ this.slackConfig = parsed.data;
46
+ this.app = new App({
47
+ token: this.slackConfig.botToken,
48
+ appToken: this.slackConfig.appToken,
49
+ signingSecret: this.slackConfig.signingSecret,
50
+ socketMode: this.slackConfig.socketMode,
51
+ port: this.slackConfig.port
52
+ });
53
+ this.app.message(async ({ message, say }) => {
54
+ const msg = message;
55
+ if (msg.bot_id || msg.subtype) return;
56
+ const normalized = MessageNormalizer.normalize({
57
+ platformMessageId: msg.ts,
58
+ channelId: this.config?.id || "",
59
+ platform: "slack",
60
+ chatId: msg.channel,
61
+ chatType: this.getChatType(msg.channel_type),
62
+ senderId: msg.user || "",
63
+ text: msg.text || "",
64
+ threadId: msg.thread_ts,
65
+ rawData: msg,
66
+ timestamp: new Date(parseFloat(msg.ts) * 1e3)
67
+ });
68
+ this.emitMessage(normalized);
69
+ });
70
+ this.app.event("app_mention", async ({ event }) => {
71
+ const normalized = MessageNormalizer.normalize({
72
+ platformMessageId: event.ts,
73
+ channelId: this.config?.id || "",
74
+ platform: "slack",
75
+ chatId: event.channel,
76
+ chatType: "channel",
77
+ senderId: event.user || "",
78
+ text: event.text || "",
79
+ threadId: event.thread_ts,
80
+ rawData: event,
81
+ timestamp: new Date(parseFloat(event.ts) * 1e3)
82
+ });
83
+ this.emitMessage(normalized);
84
+ if (this.mentionHandler) {
85
+ await this.mentionHandler({
86
+ channel: event.channel,
87
+ user: event.user || "",
88
+ text: event.text || "",
89
+ ts: event.ts,
90
+ thread_ts: event.thread_ts
91
+ });
92
+ }
93
+ });
94
+ for (const [command, handler] of this.slashCommandHandlers) {
95
+ this.app.command(command, async ({ command: cmd, ack }) => {
96
+ await ack();
97
+ await handler({
98
+ channel_id: cmd.channel_id,
99
+ user_id: cmd.user_id,
100
+ text: cmd.text,
101
+ trigger_id: cmd.trigger_id
102
+ });
103
+ });
104
+ }
105
+ await this.app.start();
106
+ }
107
+ async disconnect() {
108
+ if (this.app) {
109
+ await this.app.stop();
110
+ this.app = null;
111
+ }
112
+ this.slackConfig = null;
113
+ this.sendQueue = [];
114
+ this.messageTimestamps = [];
115
+ }
116
+ // ----- Message Sending -----
117
+ async sendMessage(message) {
118
+ if (!this.app) {
119
+ return { success: false, error: "Slack app not connected" };
120
+ }
121
+ try {
122
+ await this.enqueueRateLimited(async () => {
123
+ });
124
+ const result = await this.app.client.chat.postMessage({
125
+ channel: message.chatId,
126
+ text: message.text || "",
127
+ thread_ts: message.threadId,
128
+ mrkdwn: message.markdown ?? true
129
+ });
130
+ return {
131
+ success: result.ok ?? false,
132
+ platformMessageId: result.ts,
133
+ deliveredAt: /* @__PURE__ */ new Date()
134
+ };
135
+ } catch (error) {
136
+ return {
137
+ success: false,
138
+ error: error instanceof Error ? error.message : String(error)
139
+ };
140
+ }
141
+ }
142
+ /**
143
+ * Send a message with Block Kit blocks.
144
+ */
145
+ async sendBlocks(channelId, blocks, text) {
146
+ if (!this.app) {
147
+ return { success: false, error: "Slack app not connected" };
148
+ }
149
+ try {
150
+ await this.enforceRateLimit();
151
+ const result = await this.app.client.chat.postMessage({
152
+ channel: channelId,
153
+ blocks,
154
+ text: text || ""
155
+ });
156
+ return {
157
+ success: result.ok ?? false,
158
+ platformMessageId: result.ts,
159
+ deliveredAt: /* @__PURE__ */ new Date()
160
+ };
161
+ } catch (error) {
162
+ return {
163
+ success: false,
164
+ error: error instanceof Error ? error.message : String(error)
165
+ };
166
+ }
167
+ }
168
+ // ----- Delete Message -----
169
+ async deleteMessage(platformMessageId, chatId) {
170
+ if (!this.app) return false;
171
+ try {
172
+ const result = await this.app.client.chat.delete({
173
+ channel: chatId,
174
+ ts: platformMessageId
175
+ });
176
+ return result.ok ?? false;
177
+ } catch {
178
+ return false;
179
+ }
180
+ }
181
+ // ----- Capabilities -----
182
+ getCapabilities() {
183
+ return {
184
+ supportedMedia: ["image", "audio", "video", "file"],
185
+ maxTextLength: 4e4,
186
+ supportsThreads: true,
187
+ supportsReactions: true,
188
+ supportsEditing: true,
189
+ supportsDeleting: true,
190
+ supportsTypingIndicator: false,
191
+ supportsReadReceipts: false,
192
+ supportsActions: true,
193
+ supportsGroupChat: true,
194
+ supportsMarkdown: true,
195
+ maxFileSize: 1024 * 1024 * 1024,
196
+ // 1GB
197
+ platformSpecific: {
198
+ supportsBlockKit: true,
199
+ supportsSlashCommands: true,
200
+ supportsSocketMode: true,
201
+ supportsAppMention: true,
202
+ supportsThreadReplies: true
203
+ }
204
+ };
205
+ }
206
+ // ----- Health Check -----
207
+ async healthCheck() {
208
+ if (!this.app) {
209
+ return { status: "disconnected", details: "Slack app not initialized" };
210
+ }
211
+ try {
212
+ const result = await this.app.client.auth.test();
213
+ if (result.ok) {
214
+ return {
215
+ status: "healthy",
216
+ details: `Slack bot: @${result.user} in ${result.team}`
217
+ };
218
+ }
219
+ return { status: "degraded", details: `auth.test returned ok=false` };
220
+ } catch (error) {
221
+ return {
222
+ status: "unhealthy",
223
+ details: error instanceof Error ? error.message : String(error)
224
+ };
225
+ }
226
+ }
227
+ // ----- Optional Overrides -----
228
+ async editMessage(platformMessageId, message) {
229
+ if (!this.app) {
230
+ return { success: false, error: "Slack app not connected" };
231
+ }
232
+ try {
233
+ const result = await this.app.client.chat.update({
234
+ channel: message.chatId || "",
235
+ ts: platformMessageId,
236
+ text: message.text || ""
237
+ });
238
+ return {
239
+ success: result.ok ?? false,
240
+ platformMessageId: result.ts
241
+ };
242
+ } catch (error) {
243
+ return {
244
+ success: false,
245
+ error: error instanceof Error ? error.message : String(error)
246
+ };
247
+ }
248
+ }
249
+ async addReaction(platformMessageId, chatId, emoji) {
250
+ if (!this.app) return false;
251
+ try {
252
+ const result = await this.app.client.reactions.add({
253
+ channel: chatId,
254
+ timestamp: platformMessageId,
255
+ name: emoji.replace(/:/g, "")
256
+ });
257
+ return result.ok ?? false;
258
+ } catch {
259
+ return false;
260
+ }
261
+ }
262
+ // ----- Slash Command Registration -----
263
+ onSlashCommand(command, handler) {
264
+ this.slashCommandHandlers.set(command, handler);
265
+ if (this.app) {
266
+ this.app.command(command, async ({ command: cmd, ack }) => {
267
+ await ack();
268
+ await handler({
269
+ channel_id: cmd.channel_id,
270
+ user_id: cmd.user_id,
271
+ text: cmd.text,
272
+ trigger_id: cmd.trigger_id
273
+ });
274
+ });
275
+ }
276
+ }
277
+ // ----- Mention Handler Registration -----
278
+ onMention(handler) {
279
+ this.mentionHandler = handler;
280
+ }
281
+ // ----- Signature Verification -----
282
+ /**
283
+ * Verify Slack request signature using HMAC-SHA256 via crypto.subtle.
284
+ * Used for HTTP Events API mode (not needed for Socket Mode).
285
+ */
286
+ static async verifySignature(signingSecret, body, timestamp, signature) {
287
+ const now = Math.floor(Date.now() / 1e3);
288
+ if (Math.abs(now - parseInt(timestamp, 10)) > 300) {
289
+ return false;
290
+ }
291
+ const encoder = new TextEncoder();
292
+ const sigBaseString = `v0:${timestamp}:${body}`;
293
+ const key = await crypto.subtle.importKey(
294
+ "raw",
295
+ encoder.encode(signingSecret),
296
+ { name: "HMAC", hash: "SHA-256" },
297
+ false,
298
+ ["sign"]
299
+ );
300
+ const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(sigBaseString));
301
+ const computedHex = `v0=${Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
302
+ const computedBytes = encoder.encode(computedHex);
303
+ const expectedBytes = encoder.encode(signature);
304
+ if (computedBytes.length !== expectedBytes.length) return false;
305
+ let diff = 0;
306
+ for (let i = 0; i < computedBytes.length; i++) {
307
+ diff |= computedBytes[i] ^ expectedBytes[i];
308
+ }
309
+ return diff === 0;
310
+ }
311
+ // ----- Internal: Rate Limiting -----
312
+ async enforceRateLimit() {
313
+ const now = Date.now();
314
+ this.messageTimestamps = this.messageTimestamps.filter((t) => now - t < 1e3);
315
+ if (this.messageTimestamps.length >= this.rateLimitPerSecond) {
316
+ const oldestInWindow = this.messageTimestamps[0];
317
+ const waitMs = 1e3 - (now - oldestInWindow);
318
+ if (waitMs > 0) {
319
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
320
+ }
321
+ }
322
+ this.messageTimestamps.push(Date.now());
323
+ }
324
+ async enqueueRateLimited(fn) {
325
+ return new Promise((resolve, reject) => {
326
+ this.sendQueue.push({ fn, resolve, reject });
327
+ this.processQueue();
328
+ });
329
+ }
330
+ async processQueue() {
331
+ if (this.processingQueue) return;
332
+ this.processingQueue = true;
333
+ while (this.sendQueue.length > 0) {
334
+ const item = this.sendQueue.shift();
335
+ try {
336
+ await this.enforceRateLimit();
337
+ await item.fn();
338
+ item.resolve();
339
+ } catch (error) {
340
+ item.reject(error instanceof Error ? error : new Error(String(error)));
341
+ }
342
+ }
343
+ this.processingQueue = false;
344
+ }
345
+ // ----- Internal: Chat Type Mapping -----
346
+ getChatType(channelType) {
347
+ switch (channelType) {
348
+ case "im":
349
+ return "dm";
350
+ case "mpim":
351
+ return "group";
352
+ case "channel":
353
+ case "group":
354
+ return "channel";
355
+ default:
356
+ return "channel";
357
+ }
358
+ }
359
+ };
360
+
361
+ // src/slack-channel.ts
362
+ var LOG_LEVELS = {
363
+ debug: 0,
364
+ info: 1,
365
+ warn: 2,
366
+ error: 3
367
+ };
368
+ function createLogger(level = "info") {
369
+ const threshold = LOG_LEVELS[level] ?? 1;
370
+ const prefix = "[agentforge:slack]";
371
+ return {
372
+ debug: (...args) => {
373
+ if (threshold <= 0) console.log(`${prefix} [DEBUG]`, ...args);
374
+ },
375
+ info: (...args) => {
376
+ if (threshold <= 1) console.log(`${prefix}`, ...args);
377
+ },
378
+ warn: (...args) => {
379
+ if (threshold <= 2) console.warn(`${prefix} [WARN]`, ...args);
380
+ },
381
+ error: (...args) => {
382
+ if (threshold <= 3) console.error(`${prefix} [ERROR]`, ...args);
383
+ }
384
+ };
385
+ }
386
+ var ConvexHttpApi = class {
387
+ baseUrl;
388
+ constructor(deploymentUrl) {
389
+ this.baseUrl = deploymentUrl.replace(/\/$/, "");
390
+ }
391
+ async query(functionPath, args = {}) {
392
+ const response = await fetch(`${this.baseUrl}/api/query`, {
393
+ method: "POST",
394
+ headers: { "Content-Type": "application/json" },
395
+ body: JSON.stringify({ path: functionPath, args })
396
+ });
397
+ if (!response.ok) {
398
+ const text = await response.text();
399
+ throw new Error(`Convex query ${functionPath} failed: ${response.status} ${text}`);
400
+ }
401
+ const data = await response.json();
402
+ if (data.status === "error") throw new Error(`Convex query ${functionPath} error: ${data.errorMessage}`);
403
+ return data.value;
404
+ }
405
+ async mutation(functionPath, args = {}) {
406
+ const response = await fetch(`${this.baseUrl}/api/mutation`, {
407
+ method: "POST",
408
+ headers: { "Content-Type": "application/json" },
409
+ body: JSON.stringify({ path: functionPath, args })
410
+ });
411
+ if (!response.ok) {
412
+ const text = await response.text();
413
+ throw new Error(`Convex mutation ${functionPath} failed: ${response.status} ${text}`);
414
+ }
415
+ const data = await response.json();
416
+ if (data.status === "error") throw new Error(`Convex mutation ${functionPath} error: ${data.errorMessage}`);
417
+ return data.value;
418
+ }
419
+ async action(functionPath, args = {}) {
420
+ const response = await fetch(`${this.baseUrl}/api/action`, {
421
+ method: "POST",
422
+ headers: { "Content-Type": "application/json" },
423
+ body: JSON.stringify({ path: functionPath, args })
424
+ });
425
+ if (!response.ok) {
426
+ const text = await response.text();
427
+ throw new Error(`Convex action ${functionPath} failed: ${response.status} ${text}`);
428
+ }
429
+ const data = await response.json();
430
+ if (data.status === "error") throw new Error(`Convex action ${functionPath} error: ${data.errorMessage}`);
431
+ return data.value;
432
+ }
433
+ };
434
+ var SlackChannel = class {
435
+ adapter;
436
+ convex;
437
+ config;
438
+ threadMap = /* @__PURE__ */ new Map();
439
+ logger;
440
+ processingMessages = /* @__PURE__ */ new Set();
441
+ isRunning = false;
442
+ constructor(config) {
443
+ this.config = config;
444
+ this.adapter = new SlackAdapter();
445
+ this.convex = new ConvexHttpApi(config.convexUrl);
446
+ this.logger = createLogger(config.logLevel);
447
+ }
448
+ async start() {
449
+ if (this.isRunning) {
450
+ this.logger.warn("Slack channel is already running");
451
+ return;
452
+ }
453
+ this.logger.info("Starting Slack channel...");
454
+ this.logger.info(`Agent ID: ${this.config.agentId}`);
455
+ this.logger.info(`Convex URL: ${this.config.convexUrl}`);
456
+ this.logger.info(`Mode: ${this.config.socketMode !== false ? "Socket Mode" : "Events API"}`);
457
+ try {
458
+ const agent = await this.convex.query("agents:get", { id: this.config.agentId });
459
+ if (!agent) {
460
+ throw new Error(
461
+ `Agent "${this.config.agentId}" not found in Convex. Create it first with: agentforge agents create`
462
+ );
463
+ }
464
+ const agentData = agent;
465
+ this.logger.info(`Agent: ${agentData.name} (${agentData.model} via ${agentData.provider})`);
466
+ } catch (error) {
467
+ if (error instanceof Error && error.message.includes("not found")) {
468
+ throw error;
469
+ }
470
+ this.logger.warn("Could not verify agent (Convex may be unreachable). Continuing...");
471
+ }
472
+ this.adapter.on(this.handleEvent.bind(this));
473
+ const channelConfig = {
474
+ id: `slack-${this.config.agentId}`,
475
+ platform: "slack",
476
+ orgId: "default",
477
+ agentId: this.config.agentId,
478
+ enabled: true,
479
+ credentials: {
480
+ botToken: this.config.botToken,
481
+ appToken: this.config.appToken,
482
+ signingSecret: this.config.signingSecret
483
+ },
484
+ settings: {
485
+ socketMode: this.config.socketMode ?? true,
486
+ port: this.config.port ?? 3002
487
+ },
488
+ autoReconnect: true,
489
+ reconnectIntervalMs: 5e3,
490
+ maxReconnectAttempts: 20
491
+ };
492
+ await this.adapter.start(channelConfig);
493
+ this.isRunning = true;
494
+ this.logger.info("Slack channel started successfully!");
495
+ this.logger.info("Bot is listening for messages...");
496
+ }
497
+ async stop() {
498
+ if (!this.isRunning) return;
499
+ this.logger.info("Stopping Slack channel...");
500
+ await this.adapter.stop();
501
+ this.isRunning = false;
502
+ this.threadMap.clear();
503
+ this.processingMessages.clear();
504
+ this.logger.info("Slack channel stopped.");
505
+ }
506
+ getThreadMap() {
507
+ return this.threadMap;
508
+ }
509
+ getAdapter() {
510
+ return this.adapter;
511
+ }
512
+ get running() {
513
+ return this.isRunning;
514
+ }
515
+ // ----- Internal: Event Handling -----
516
+ async handleEvent(event) {
517
+ switch (event.type) {
518
+ case "message":
519
+ await this.handleInboundMessage(event.data);
520
+ break;
521
+ case "connection_state":
522
+ this.logger.debug("Connection state:", event.data.state);
523
+ break;
524
+ case "error":
525
+ this.logger.error("Adapter error:", event.data.error.message);
526
+ break;
527
+ default:
528
+ this.logger.debug("Unhandled event type:", event.type);
529
+ }
530
+ }
531
+ async handleInboundMessage(message) {
532
+ if (!message.text?.trim()) {
533
+ this.logger.debug("Skipping empty message");
534
+ return;
535
+ }
536
+ const dedupKey = `${message.chatId}:${message.platformMessageId}`;
537
+ if (this.processingMessages.has(dedupKey)) {
538
+ this.logger.debug("Skipping duplicate message:", dedupKey);
539
+ return;
540
+ }
541
+ this.processingMessages.add(dedupKey);
542
+ const senderName = message.sender.displayName || message.sender.username || "Unknown";
543
+ this.logger.info(`Message from ${senderName} (channel ${message.chatId}): ${message.text}`);
544
+ try {
545
+ await this.routeToAgent(message);
546
+ } catch (error) {
547
+ this.logger.error("Error handling message:", error);
548
+ try {
549
+ await this.adapter.sendMessage({
550
+ chatId: message.chatId,
551
+ text: "Sorry, I encountered an error processing your message. Please try again.",
552
+ threadId: message.threadId
553
+ });
554
+ } catch {
555
+ this.logger.error("Failed to send error message to user");
556
+ }
557
+ } finally {
558
+ setTimeout(() => {
559
+ this.processingMessages.delete(dedupKey);
560
+ }, 3e4);
561
+ }
562
+ }
563
+ // ----- Internal: Agent Routing -----
564
+ async routeToAgent(message) {
565
+ const threadKey = `${message.chatId}:${message.sender.platformUserId}`;
566
+ const threadId = await this.getOrCreateThread(threadKey, message.sender.displayName);
567
+ const userId = this.config.userId || `slack:${message.sender.platformUserId}`;
568
+ this.logger.debug(`Sending to agent ${this.config.agentId}, thread ${threadId}`);
569
+ const result = await this.convex.action("chat:sendMessage", {
570
+ agentId: this.config.agentId,
571
+ threadId,
572
+ content: message.text,
573
+ userId
574
+ });
575
+ if (result?.response) {
576
+ const chunks = this.splitMessage(result.response, 4e3);
577
+ for (const chunk of chunks) {
578
+ await this.adapter.sendMessage({
579
+ chatId: message.chatId,
580
+ text: chunk,
581
+ threadId: message.threadId
582
+ });
583
+ }
584
+ if (result.usage) {
585
+ this.logger.debug(`Tokens used: ${result.usage.totalTokens}`);
586
+ }
587
+ } else {
588
+ await this.adapter.sendMessage({
589
+ chatId: message.chatId,
590
+ text: "I received your message but couldn't generate a response. Please try again.",
591
+ threadId: message.threadId
592
+ });
593
+ }
594
+ }
595
+ // ----- Internal: Thread Management -----
596
+ async getOrCreateThread(threadKey, senderName) {
597
+ const cached = this.threadMap.get(threadKey);
598
+ if (cached) return cached;
599
+ const threadName = senderName ? `Slack: ${senderName}` : `Slack ${threadKey}`;
600
+ const userId = this.config.userId || `slack:${threadKey}`;
601
+ const threadId = await this.convex.mutation("chat:createThread", {
602
+ agentId: this.config.agentId,
603
+ name: threadName,
604
+ userId
605
+ });
606
+ this.threadMap.set(threadKey, threadId);
607
+ this.logger.info(`Created new thread ${threadId} for ${threadKey}`);
608
+ return threadId;
609
+ }
610
+ // ----- Internal: Utilities -----
611
+ splitMessage(text, maxLength) {
612
+ if (text.length <= maxLength) return [text];
613
+ const chunks = [];
614
+ let remaining = text;
615
+ while (remaining.length > 0) {
616
+ if (remaining.length <= maxLength) {
617
+ chunks.push(remaining);
618
+ break;
619
+ }
620
+ let splitIdx = remaining.lastIndexOf("\n\n", maxLength);
621
+ if (splitIdx === -1 || splitIdx < maxLength / 2) {
622
+ splitIdx = remaining.lastIndexOf("\n", maxLength);
623
+ }
624
+ if (splitIdx === -1 || splitIdx < maxLength / 2) {
625
+ splitIdx = remaining.lastIndexOf(" ", maxLength);
626
+ }
627
+ if (splitIdx === -1 || splitIdx < maxLength / 2) {
628
+ splitIdx = maxLength;
629
+ }
630
+ chunks.push(remaining.substring(0, splitIdx));
631
+ remaining = remaining.substring(splitIdx).trimStart();
632
+ }
633
+ return chunks;
634
+ }
635
+ };
636
+ async function startSlackChannel(overrides = {}) {
637
+ const botToken = overrides.botToken || process.env.SLACK_BOT_TOKEN;
638
+ const appToken = overrides.appToken || process.env.SLACK_APP_TOKEN;
639
+ const signingSecret = overrides.signingSecret || process.env.SLACK_SIGNING_SECRET;
640
+ const convexUrl = overrides.convexUrl || process.env.CONVEX_URL;
641
+ const agentId = overrides.agentId || process.env.AGENTFORGE_AGENT_ID;
642
+ if (!botToken) {
643
+ throw new Error(
644
+ "SLACK_BOT_TOKEN is required. Set it in your .env file or pass it as botToken in the config."
645
+ );
646
+ }
647
+ if (!appToken) {
648
+ throw new Error(
649
+ "SLACK_APP_TOKEN is required for Socket Mode. Set it in your .env file or pass it as appToken in the config."
650
+ );
651
+ }
652
+ if (!signingSecret) {
653
+ throw new Error(
654
+ "SLACK_SIGNING_SECRET is required. Set it in your .env file or pass it as signingSecret in the config."
655
+ );
656
+ }
657
+ if (!convexUrl) {
658
+ throw new Error(
659
+ "CONVEX_URL is required. Set it in your .env file or pass it as convexUrl in the config."
660
+ );
661
+ }
662
+ if (!agentId) {
663
+ throw new Error(
664
+ "Agent ID is required. Pass it as agentId in the config or set AGENTFORGE_AGENT_ID env var."
665
+ );
666
+ }
667
+ const channel = new SlackChannel({
668
+ botToken,
669
+ appToken,
670
+ signingSecret,
671
+ convexUrl,
672
+ agentId,
673
+ socketMode: overrides.socketMode,
674
+ port: overrides.port,
675
+ userId: overrides.userId,
676
+ logLevel: overrides.logLevel
677
+ });
678
+ const shutdown = async () => {
679
+ console.log("\nShutting down Slack channel...");
680
+ await channel.stop();
681
+ process.exit(0);
682
+ };
683
+ process.on("SIGINT", shutdown);
684
+ process.on("SIGTERM", shutdown);
685
+ await channel.start();
686
+ return channel;
687
+ }
688
+ export {
689
+ SlackAdapter,
690
+ SlackChannel,
691
+ slackConfigSchema,
692
+ startSlackChannel
693
+ };
694
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/slack-adapter.ts","../src/types.ts","../src/slack-channel.ts"],"sourcesContent":["/**\n * Slack Channel Adapter for AgentForge.\n *\n * Implements the ChannelAdapter interface using Slack Bolt.js with\n * Socket Mode and Events API support.\n *\n * Features:\n * - Socket Mode (WebSocket) and HTTP Events API\n * - Block Kit rich messages\n * - Slash command handling\n * - app_mention event handling\n * - Signature verification (HMAC-SHA256 via crypto.subtle)\n * - Rate limiting with queue and delay\n * - Zod config validation\n *\n * @packageDocumentation\n */\n\nimport { App } from '@slack/bolt';\nimport {\n ChannelAdapter,\n MessageNormalizer,\n type ChannelConfig,\n type ChannelCapabilities,\n type HealthStatus,\n type OutboundMessage,\n type SendResult,\n type ChatType,\n} from '@agentforge-ai/core';\nimport { slackConfigSchema, type SlackConfig, type SlackBlock } from './types.js';\n\n// =====================================================\n// Slack Adapter\n// =====================================================\n\nexport class SlackAdapter extends ChannelAdapter {\n readonly platform = 'slack';\n\n private app: App | null = null;\n private slackConfig: SlackConfig | null = null;\n\n // Rate limiting\n private messageTimestamps: number[] = [];\n private readonly rateLimitPerSecond: number = 50; // Slack tier 3 limit\n private sendQueue: Array<{ fn: () => Promise<void>; resolve: () => void; reject: (e: Error) => void }> = [];\n private processingQueue = false;\n\n // Event handlers registered by consumers\n private mentionHandler: ((event: { channel: string; user: string; text: string; ts: string; thread_ts?: string }) => void | Promise<void>) | null = null;\n private slashCommandHandlers: Map<string, (payload: { channel_id: string; user_id: string; text: string; trigger_id: string }) => void | Promise<void>> = new Map();\n\n // ----- Lifecycle -----\n\n async connect(config: ChannelConfig): Promise<void> {\n const parsed = slackConfigSchema.safeParse({\n botToken: config.credentials.botToken,\n appToken: config.credentials.appToken,\n signingSecret: config.credentials.signingSecret,\n socketMode: config.settings?.socketMode ?? true,\n port: config.settings?.port ?? 3002,\n });\n\n if (!parsed.success) {\n const issues = parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ');\n throw new Error(`Invalid Slack config: ${issues}`);\n }\n\n this.slackConfig = parsed.data;\n\n this.app = new App({\n token: this.slackConfig.botToken,\n appToken: this.slackConfig.appToken,\n signingSecret: this.slackConfig.signingSecret,\n socketMode: this.slackConfig.socketMode,\n port: this.slackConfig.port,\n });\n\n // Wire up message events\n this.app.message(async ({ message, say }) => {\n // Skip bot messages and subtypes (edits, deletes, etc.)\n const msg = message as any;\n if (msg.bot_id || msg.subtype) return;\n\n const normalized = MessageNormalizer.normalize({\n platformMessageId: msg.ts,\n channelId: this.config?.id || '',\n platform: 'slack',\n chatId: msg.channel,\n chatType: this.getChatType(msg.channel_type),\n senderId: msg.user || '',\n text: msg.text || '',\n threadId: msg.thread_ts,\n rawData: msg,\n timestamp: new Date(parseFloat(msg.ts) * 1000),\n });\n\n this.emitMessage(normalized);\n });\n\n // Wire up app_mention events\n this.app.event('app_mention', async ({ event }) => {\n const normalized = MessageNormalizer.normalize({\n platformMessageId: event.ts,\n channelId: this.config?.id || '',\n platform: 'slack',\n chatId: event.channel,\n chatType: 'channel',\n senderId: event.user || '',\n text: event.text || '',\n threadId: (event as any).thread_ts,\n rawData: event as unknown as Record<string, unknown>,\n timestamp: new Date(parseFloat(event.ts) * 1000),\n });\n\n this.emitMessage(normalized);\n\n if (this.mentionHandler) {\n await this.mentionHandler({\n channel: event.channel,\n user: event.user || '',\n text: event.text || '',\n ts: event.ts,\n thread_ts: (event as any).thread_ts,\n });\n }\n });\n\n // Register any deferred slash commands\n for (const [command, handler] of this.slashCommandHandlers) {\n this.app.command(command, async ({ command: cmd, ack }) => {\n await ack();\n await handler({\n channel_id: cmd.channel_id,\n user_id: cmd.user_id,\n text: cmd.text,\n trigger_id: cmd.trigger_id,\n });\n });\n }\n\n await this.app.start();\n }\n\n async disconnect(): Promise<void> {\n if (this.app) {\n await this.app.stop();\n this.app = null;\n }\n this.slackConfig = null;\n this.sendQueue = [];\n this.messageTimestamps = [];\n }\n\n // ----- Message Sending -----\n\n async sendMessage(message: OutboundMessage): Promise<SendResult> {\n if (!this.app) {\n return { success: false, error: 'Slack app not connected' };\n }\n\n try {\n await this.enqueueRateLimited(async () => {\n // noop — actual send below\n });\n\n const result = await this.app.client.chat.postMessage({\n channel: message.chatId,\n text: message.text || '',\n thread_ts: message.threadId,\n mrkdwn: message.markdown ?? true,\n });\n\n return {\n success: result.ok ?? false,\n platformMessageId: result.ts,\n deliveredAt: new Date(),\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Send a message with Block Kit blocks.\n */\n async sendBlocks(channelId: string, blocks: SlackBlock[], text?: string): Promise<SendResult> {\n if (!this.app) {\n return { success: false, error: 'Slack app not connected' };\n }\n\n try {\n await this.enforceRateLimit();\n\n const result = await this.app.client.chat.postMessage({\n channel: channelId,\n blocks: blocks as any[],\n text: text || '',\n });\n\n return {\n success: result.ok ?? false,\n platformMessageId: result.ts,\n deliveredAt: new Date(),\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n // ----- Delete Message -----\n\n override async deleteMessage(platformMessageId: string, chatId: string): Promise<boolean> {\n if (!this.app) return false;\n\n try {\n const result = await this.app.client.chat.delete({\n channel: chatId,\n ts: platformMessageId,\n });\n return result.ok ?? false;\n } catch {\n return false;\n }\n }\n\n // ----- Capabilities -----\n\n getCapabilities(): ChannelCapabilities {\n return {\n supportedMedia: ['image', 'audio', 'video', 'file'],\n maxTextLength: 40000,\n supportsThreads: true,\n supportsReactions: true,\n supportsEditing: true,\n supportsDeleting: true,\n supportsTypingIndicator: false,\n supportsReadReceipts: false,\n supportsActions: true,\n supportsGroupChat: true,\n supportsMarkdown: true,\n maxFileSize: 1024 * 1024 * 1024, // 1GB\n platformSpecific: {\n supportsBlockKit: true,\n supportsSlashCommands: true,\n supportsSocketMode: true,\n supportsAppMention: true,\n supportsThreadReplies: true,\n },\n };\n }\n\n // ----- Health Check -----\n\n async healthCheck(): Promise<{ status: HealthStatus; details?: string }> {\n if (!this.app) {\n return { status: 'disconnected', details: 'Slack app not initialized' };\n }\n\n try {\n const result = await this.app.client.auth.test();\n if (result.ok) {\n return {\n status: 'healthy',\n details: `Slack bot: @${result.user} in ${result.team}`,\n };\n }\n return { status: 'degraded', details: `auth.test returned ok=false` };\n } catch (error) {\n return {\n status: 'unhealthy',\n details: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n // ----- Optional Overrides -----\n\n override async editMessage(\n platformMessageId: string,\n message: Partial<OutboundMessage>\n ): Promise<SendResult> {\n if (!this.app) {\n return { success: false, error: 'Slack app not connected' };\n }\n\n try {\n const result = await this.app.client.chat.update({\n channel: message.chatId || '',\n ts: platformMessageId,\n text: message.text || '',\n });\n\n return {\n success: result.ok ?? false,\n platformMessageId: result.ts,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n override async addReaction(\n platformMessageId: string,\n chatId: string,\n emoji: string\n ): Promise<boolean> {\n if (!this.app) return false;\n\n try {\n const result = await this.app.client.reactions.add({\n channel: chatId,\n timestamp: platformMessageId,\n name: emoji.replace(/:/g, ''),\n });\n return result.ok ?? false;\n } catch {\n return false;\n }\n }\n\n // ----- Slash Command Registration -----\n\n onSlashCommand(\n command: string,\n handler: (payload: { channel_id: string; user_id: string; text: string; trigger_id: string }) => void | Promise<void>\n ): void {\n this.slashCommandHandlers.set(command, handler);\n\n if (this.app) {\n this.app.command(command, async ({ command: cmd, ack }) => {\n await ack();\n await handler({\n channel_id: cmd.channel_id,\n user_id: cmd.user_id,\n text: cmd.text,\n trigger_id: cmd.trigger_id,\n });\n });\n }\n }\n\n // ----- Mention Handler Registration -----\n\n onMention(\n handler: (event: { channel: string; user: string; text: string; ts: string; thread_ts?: string }) => void | Promise<void>\n ): void {\n this.mentionHandler = handler;\n }\n\n // ----- Signature Verification -----\n\n /**\n * Verify Slack request signature using HMAC-SHA256 via crypto.subtle.\n * Used for HTTP Events API mode (not needed for Socket Mode).\n */\n static async verifySignature(\n signingSecret: string,\n body: string,\n timestamp: string,\n signature: string\n ): Promise<boolean> {\n // Check timestamp freshness (5 min window)\n const now = Math.floor(Date.now() / 1000);\n if (Math.abs(now - parseInt(timestamp, 10)) > 300) {\n return false;\n }\n\n const encoder = new TextEncoder();\n const sigBaseString = `v0:${timestamp}:${body}`;\n\n const key = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(signingSecret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n );\n\n const sig = await crypto.subtle.sign('HMAC', key, encoder.encode(sigBaseString));\n const computedHex = `v0=${Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, '0')).join('')}`;\n\n // Constant-time comparison\n const computedBytes = encoder.encode(computedHex);\n const expectedBytes = encoder.encode(signature);\n\n if (computedBytes.length !== expectedBytes.length) return false;\n\n let diff = 0;\n for (let i = 0; i < computedBytes.length; i++) {\n diff |= computedBytes[i] ^ expectedBytes[i];\n }\n return diff === 0;\n }\n\n // ----- Internal: Rate Limiting -----\n\n private async enforceRateLimit(): Promise<void> {\n const now = Date.now();\n this.messageTimestamps = this.messageTimestamps.filter((t) => now - t < 1000);\n\n if (this.messageTimestamps.length >= this.rateLimitPerSecond) {\n const oldestInWindow = this.messageTimestamps[0];\n const waitMs = 1000 - (now - oldestInWindow);\n if (waitMs > 0) {\n await new Promise<void>((resolve) => setTimeout(resolve, waitMs));\n }\n }\n\n this.messageTimestamps.push(Date.now());\n }\n\n private async enqueueRateLimited(fn: () => Promise<void>): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.sendQueue.push({ fn, resolve, reject });\n this.processQueue();\n });\n }\n\n private async processQueue(): Promise<void> {\n if (this.processingQueue) return;\n this.processingQueue = true;\n\n while (this.sendQueue.length > 0) {\n const item = this.sendQueue.shift()!;\n try {\n await this.enforceRateLimit();\n await item.fn();\n item.resolve();\n } catch (error) {\n item.reject(error instanceof Error ? error : new Error(String(error)));\n }\n }\n\n this.processingQueue = false;\n }\n\n // ----- Internal: Chat Type Mapping -----\n\n private getChatType(channelType?: string): ChatType {\n switch (channelType) {\n case 'im':\n return 'dm';\n case 'mpim':\n return 'group';\n case 'channel':\n case 'group':\n return 'channel';\n default:\n return 'channel';\n }\n }\n}\n","import { z } from 'zod';\n\n// =====================================================\n// Slack Configuration\n// =====================================================\n\nexport const slackConfigSchema = z.object({\n botToken: z.string().min(1, 'Bot token is required').startsWith('xoxb-', 'Bot token must start with xoxb-'),\n appToken: z.string().min(1, 'App token is required').startsWith('xapp-', 'App token must start with xapp-'),\n signingSecret: z.string().min(1, 'Signing secret is required'),\n socketMode: z.boolean().default(true),\n port: z.number().int().min(1).max(65535).default(3002),\n});\n\nexport type SlackConfig = z.infer<typeof slackConfigSchema>;\n\n// =====================================================\n// Slack Message Types\n// =====================================================\n\nexport interface SlackMessage {\n type: string;\n subtype?: string;\n channel: string;\n user: string;\n text: string;\n ts: string;\n thread_ts?: string;\n bot_id?: string;\n blocks?: SlackBlock[];\n files?: SlackFile[];\n}\n\nexport interface SlackFile {\n id: string;\n name: string;\n mimetype: string;\n url_private: string;\n size: number;\n}\n\n// =====================================================\n// Slack Event Types\n// =====================================================\n\nexport interface SlackEvent {\n type: string;\n event_ts: string;\n user?: string;\n channel?: string;\n text?: string;\n ts?: string;\n thread_ts?: string;\n bot_id?: string;\n subtype?: string;\n command?: string;\n}\n\n// =====================================================\n// Slack Block Kit Types\n// =====================================================\n\nexport type SlackBlock =\n | SlackSectionBlock\n | SlackDividerBlock\n | SlackActionsBlock\n | SlackHeaderBlock\n | SlackContextBlock\n | SlackImageBlock;\n\nexport interface SlackSectionBlock {\n type: 'section';\n text?: SlackTextObject;\n fields?: SlackTextObject[];\n accessory?: SlackBlockElement;\n block_id?: string;\n}\n\nexport interface SlackDividerBlock {\n type: 'divider';\n block_id?: string;\n}\n\nexport interface SlackActionsBlock {\n type: 'actions';\n elements: SlackBlockElement[];\n block_id?: string;\n}\n\nexport interface SlackHeaderBlock {\n type: 'header';\n text: SlackTextObject;\n block_id?: string;\n}\n\nexport interface SlackContextBlock {\n type: 'context';\n elements: (SlackTextObject | SlackImageElement)[];\n block_id?: string;\n}\n\nexport interface SlackImageBlock {\n type: 'image';\n image_url: string;\n alt_text: string;\n title?: SlackTextObject;\n block_id?: string;\n}\n\nexport interface SlackTextObject {\n type: 'plain_text' | 'mrkdwn';\n text: string;\n emoji?: boolean;\n}\n\nexport type SlackBlockElement =\n | SlackButtonElement\n | SlackImageElement\n | SlackOverflowElement;\n\nexport interface SlackButtonElement {\n type: 'button';\n text: SlackTextObject;\n action_id: string;\n value?: string;\n url?: string;\n style?: 'primary' | 'danger';\n}\n\nexport interface SlackImageElement {\n type: 'image';\n image_url: string;\n alt_text: string;\n}\n\nexport interface SlackOverflowElement {\n type: 'overflow';\n action_id: string;\n options: Array<{\n text: SlackTextObject;\n value: string;\n }>;\n}\n","/**\n * Slack Channel for AgentForge.\n *\n * Bridges the SlackAdapter with the AgentForge Convex chat pipeline.\n * This module:\n * - Starts the Slack bot (Socket Mode or Events API)\n * - Routes incoming messages through the agent execution pipeline\n * - Creates/reuses Convex threads per Slack channel+user\n * - Stores all messages in the Convex messages table\n * - Sends agent responses back to the Slack user\n *\n * @packageDocumentation\n */\n\nimport { SlackAdapter } from './slack-adapter.js';\nimport type {\n ChannelConfig,\n InboundMessage,\n ChannelEvent,\n} from '@agentforge-ai/core';\n\n// =====================================================\n// Types\n// =====================================================\n\nexport interface SlackChannelConfig {\n /** Slack Bot Token (xoxb-...) */\n botToken: string;\n /** Slack App-Level Token (xapp-...) for Socket Mode */\n appToken: string;\n /** Slack Signing Secret */\n signingSecret: string;\n /** Agent ID to route messages to */\n agentId: string;\n /** Convex deployment URL */\n convexUrl: string;\n /** Whether to use Socket Mode (default: true) */\n socketMode?: boolean;\n /** HTTP port for Events API mode (default: 3002) */\n port?: number;\n /** User ID for Convex operations (default: 'slack') */\n userId?: string;\n /** Log level: 'debug' | 'info' | 'warn' | 'error' (default: 'info') */\n logLevel?: 'debug' | 'info' | 'warn' | 'error';\n}\n\ntype ThreadMap = Map<string, string>;\n\ninterface Logger {\n debug: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n}\n\n// =====================================================\n// Logger\n// =====================================================\n\nconst LOG_LEVELS: Record<string, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\nfunction createLogger(level: string = 'info'): Logger {\n const threshold = LOG_LEVELS[level] ?? 1;\n const prefix = '[agentforge:slack]';\n\n return {\n debug: (...args: unknown[]) => {\n if (threshold <= 0) console.log(`${prefix} [DEBUG]`, ...args);\n },\n info: (...args: unknown[]) => {\n if (threshold <= 1) console.log(`${prefix}`, ...args);\n },\n warn: (...args: unknown[]) => {\n if (threshold <= 2) console.warn(`${prefix} [WARN]`, ...args);\n },\n error: (...args: unknown[]) => {\n if (threshold <= 3) console.error(`${prefix} [ERROR]`, ...args);\n },\n };\n}\n\n// =====================================================\n// Convex HTTP Client\n// =====================================================\n\nclass ConvexHttpApi {\n private baseUrl: string;\n\n constructor(deploymentUrl: string) {\n this.baseUrl = deploymentUrl.replace(/\\/$/, '');\n }\n\n async query(functionPath: string, args: Record<string, unknown> = {}): Promise<unknown> {\n const response = await fetch(`${this.baseUrl}/api/query`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: functionPath, args }),\n });\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`Convex query ${functionPath} failed: ${response.status} ${text}`);\n }\n const data = await response.json() as { value?: unknown; status?: string; errorMessage?: string };\n if (data.status === 'error') throw new Error(`Convex query ${functionPath} error: ${data.errorMessage}`);\n return data.value;\n }\n\n async mutation(functionPath: string, args: Record<string, unknown> = {}): Promise<unknown> {\n const response = await fetch(`${this.baseUrl}/api/mutation`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: functionPath, args }),\n });\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`Convex mutation ${functionPath} failed: ${response.status} ${text}`);\n }\n const data = await response.json() as { value?: unknown; status?: string; errorMessage?: string };\n if (data.status === 'error') throw new Error(`Convex mutation ${functionPath} error: ${data.errorMessage}`);\n return data.value;\n }\n\n async action(functionPath: string, args: Record<string, unknown> = {}): Promise<unknown> {\n const response = await fetch(`${this.baseUrl}/api/action`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: functionPath, args }),\n });\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`Convex action ${functionPath} failed: ${response.status} ${text}`);\n }\n const data = await response.json() as { value?: unknown; status?: string; errorMessage?: string };\n if (data.status === 'error') throw new Error(`Convex action ${functionPath} error: ${data.errorMessage}`);\n return data.value;\n }\n}\n\n// =====================================================\n// Slack Channel Runner\n// =====================================================\n\nexport class SlackChannel {\n private adapter: SlackAdapter;\n private convex: ConvexHttpApi;\n private config: SlackChannelConfig;\n private threadMap: ThreadMap = new Map();\n private logger: Logger;\n private processingMessages: Set<string> = new Set();\n private isRunning: boolean = false;\n\n constructor(config: SlackChannelConfig) {\n this.config = config;\n this.adapter = new SlackAdapter();\n this.convex = new ConvexHttpApi(config.convexUrl);\n this.logger = createLogger(config.logLevel);\n }\n\n async start(): Promise<void> {\n if (this.isRunning) {\n this.logger.warn('Slack channel is already running');\n return;\n }\n\n this.logger.info('Starting Slack channel...');\n this.logger.info(`Agent ID: ${this.config.agentId}`);\n this.logger.info(`Convex URL: ${this.config.convexUrl}`);\n this.logger.info(`Mode: ${this.config.socketMode !== false ? 'Socket Mode' : 'Events API'}`);\n\n // Verify the agent exists\n try {\n const agent = await this.convex.query('agents:get', { id: this.config.agentId });\n if (!agent) {\n throw new Error(\n `Agent \"${this.config.agentId}\" not found in Convex. ` +\n `Create it first with: agentforge agents create`\n );\n }\n const agentData = agent as { name: string; model: string; provider: string };\n this.logger.info(`Agent: ${agentData.name} (${agentData.model} via ${agentData.provider})`);\n } catch (error) {\n if (error instanceof Error && error.message.includes('not found')) {\n throw error;\n }\n this.logger.warn('Could not verify agent (Convex may be unreachable). Continuing...');\n }\n\n // Wire up event handler\n this.adapter.on(this.handleEvent.bind(this));\n\n const channelConfig: ChannelConfig = {\n id: `slack-${this.config.agentId}`,\n platform: 'slack',\n orgId: 'default',\n agentId: this.config.agentId,\n enabled: true,\n credentials: {\n botToken: this.config.botToken,\n appToken: this.config.appToken,\n signingSecret: this.config.signingSecret,\n },\n settings: {\n socketMode: this.config.socketMode ?? true,\n port: this.config.port ?? 3002,\n },\n autoReconnect: true,\n reconnectIntervalMs: 5000,\n maxReconnectAttempts: 20,\n };\n\n await this.adapter.start(channelConfig);\n this.isRunning = true;\n\n this.logger.info('Slack channel started successfully!');\n this.logger.info('Bot is listening for messages...');\n }\n\n async stop(): Promise<void> {\n if (!this.isRunning) return;\n\n this.logger.info('Stopping Slack channel...');\n await this.adapter.stop();\n this.isRunning = false;\n this.threadMap.clear();\n this.processingMessages.clear();\n this.logger.info('Slack channel stopped.');\n }\n\n getThreadMap(): ReadonlyMap<string, string> {\n return this.threadMap;\n }\n\n getAdapter(): SlackAdapter {\n return this.adapter;\n }\n\n get running(): boolean {\n return this.isRunning;\n }\n\n // ----- Internal: Event Handling -----\n\n private async handleEvent(event: ChannelEvent): Promise<void> {\n switch (event.type) {\n case 'message':\n await this.handleInboundMessage(event.data as InboundMessage);\n break;\n case 'connection_state':\n this.logger.debug('Connection state:', (event.data as { state: string }).state);\n break;\n case 'error':\n this.logger.error('Adapter error:', (event.data as { error: Error }).error.message);\n break;\n default:\n this.logger.debug('Unhandled event type:', event.type);\n }\n }\n\n private async handleInboundMessage(message: InboundMessage): Promise<void> {\n if (!message.text?.trim()) {\n this.logger.debug('Skipping empty message');\n return;\n }\n\n // Dedup\n const dedupKey = `${message.chatId}:${message.platformMessageId}`;\n if (this.processingMessages.has(dedupKey)) {\n this.logger.debug('Skipping duplicate message:', dedupKey);\n return;\n }\n this.processingMessages.add(dedupKey);\n\n const senderName = message.sender.displayName || message.sender.username || 'Unknown';\n this.logger.info(`Message from ${senderName} (channel ${message.chatId}): ${message.text}`);\n\n try {\n await this.routeToAgent(message);\n } catch (error) {\n this.logger.error('Error handling message:', error);\n try {\n await this.adapter.sendMessage({\n chatId: message.chatId,\n text: 'Sorry, I encountered an error processing your message. Please try again.',\n threadId: message.threadId,\n });\n } catch {\n this.logger.error('Failed to send error message to user');\n }\n } finally {\n setTimeout(() => {\n this.processingMessages.delete(dedupKey);\n }, 30000);\n }\n }\n\n // ----- Internal: Agent Routing -----\n\n private async routeToAgent(message: InboundMessage): Promise<void> {\n const threadKey = `${message.chatId}:${message.sender.platformUserId}`;\n const threadId = await this.getOrCreateThread(threadKey, message.sender.displayName);\n const userId = this.config.userId || `slack:${message.sender.platformUserId}`;\n\n this.logger.debug(`Sending to agent ${this.config.agentId}, thread ${threadId}`);\n\n const result = await this.convex.action('chat:sendMessage', {\n agentId: this.config.agentId,\n threadId,\n content: message.text!,\n userId,\n }) as { success: boolean; response: string; usage?: { totalTokens: number } };\n\n if (result?.response) {\n const chunks = this.splitMessage(result.response, 4000);\n for (const chunk of chunks) {\n await this.adapter.sendMessage({\n chatId: message.chatId,\n text: chunk,\n threadId: message.threadId,\n });\n }\n\n if (result.usage) {\n this.logger.debug(`Tokens used: ${result.usage.totalTokens}`);\n }\n } else {\n await this.adapter.sendMessage({\n chatId: message.chatId,\n text: \"I received your message but couldn't generate a response. Please try again.\",\n threadId: message.threadId,\n });\n }\n }\n\n // ----- Internal: Thread Management -----\n\n private async getOrCreateThread(threadKey: string, senderName?: string): Promise<string> {\n const cached = this.threadMap.get(threadKey);\n if (cached) return cached;\n\n const threadName = senderName\n ? `Slack: ${senderName}`\n : `Slack ${threadKey}`;\n\n const userId = this.config.userId || `slack:${threadKey}`;\n\n const threadId = await this.convex.mutation('chat:createThread', {\n agentId: this.config.agentId,\n name: threadName,\n userId,\n }) as string;\n\n this.threadMap.set(threadKey, threadId);\n this.logger.info(`Created new thread ${threadId} for ${threadKey}`);\n\n return threadId;\n }\n\n // ----- Internal: Utilities -----\n\n private splitMessage(text: string, maxLength: number): string[] {\n if (text.length <= maxLength) return [text];\n\n const chunks: string[] = [];\n let remaining = text;\n\n while (remaining.length > 0) {\n if (remaining.length <= maxLength) {\n chunks.push(remaining);\n break;\n }\n\n let splitIdx = remaining.lastIndexOf('\\n\\n', maxLength);\n if (splitIdx === -1 || splitIdx < maxLength / 2) {\n splitIdx = remaining.lastIndexOf('\\n', maxLength);\n }\n if (splitIdx === -1 || splitIdx < maxLength / 2) {\n splitIdx = remaining.lastIndexOf(' ', maxLength);\n }\n if (splitIdx === -1 || splitIdx < maxLength / 2) {\n splitIdx = maxLength;\n }\n\n chunks.push(remaining.substring(0, splitIdx));\n remaining = remaining.substring(splitIdx).trimStart();\n }\n\n return chunks;\n }\n}\n\n// =====================================================\n// Convenience Factory\n// =====================================================\n\nexport async function startSlackChannel(\n overrides: Partial<SlackChannelConfig> = {}\n): Promise<SlackChannel> {\n const botToken = overrides.botToken || process.env.SLACK_BOT_TOKEN;\n const appToken = overrides.appToken || process.env.SLACK_APP_TOKEN;\n const signingSecret = overrides.signingSecret || process.env.SLACK_SIGNING_SECRET;\n const convexUrl = overrides.convexUrl || process.env.CONVEX_URL;\n const agentId = overrides.agentId || process.env.AGENTFORGE_AGENT_ID;\n\n if (!botToken) {\n throw new Error(\n 'SLACK_BOT_TOKEN is required. Set it in your .env file or pass it as botToken in the config.'\n );\n }\n if (!appToken) {\n throw new Error(\n 'SLACK_APP_TOKEN is required for Socket Mode. Set it in your .env file or pass it as appToken in the config.'\n );\n }\n if (!signingSecret) {\n throw new Error(\n 'SLACK_SIGNING_SECRET is required. Set it in your .env file or pass it as signingSecret in the config.'\n );\n }\n if (!convexUrl) {\n throw new Error(\n 'CONVEX_URL is required. Set it in your .env file or pass it as convexUrl in the config.'\n );\n }\n if (!agentId) {\n throw new Error(\n 'Agent ID is required. Pass it as agentId in the config or set AGENTFORGE_AGENT_ID env var.'\n );\n }\n\n const channel = new SlackChannel({\n botToken,\n appToken,\n signingSecret,\n convexUrl,\n agentId,\n socketMode: overrides.socketMode,\n port: overrides.port,\n userId: overrides.userId,\n logLevel: overrides.logLevel,\n });\n\n const shutdown = async () => {\n console.log('\\nShutting down Slack channel...');\n await channel.stop();\n process.exit(0);\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n await channel.start();\n return channel;\n}\n"],"mappings":";AAkBA,SAAS,WAAW;AACpB;AAAA,EACE;AAAA,EACA;AAAA,OAOK;;;AC5BP,SAAS,SAAS;AAMX,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,UAAU,EAAE,OAAO,EAAE,IAAI,GAAG,uBAAuB,EAAE,WAAW,SAAS,iCAAiC;AAAA,EAC1G,UAAU,EAAE,OAAO,EAAE,IAAI,GAAG,uBAAuB,EAAE,W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AAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,YAAY,UAAU;AAAA,IACtB,MAAM,UAAU;AAAA,IAChB,QAAQ,UAAU;AAAA,IAClB,UAAU,UAAU;AAAA,EACtB,CAAC;AAED,QAAM,WAAW,YAAY;AAC3B,YAAQ,IAAI,kCAAkC;AAC9C,UAAM,QAAQ,KAAK;AACnB,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,UAAQ,GAAG,UAAU,QAAQ;AAC7B,UAAQ,GAAG,WAAW,QAAQ;AAE9B,QAAM,QAAQ,MAAM;AACpB,SAAO;AACT;","names":[]}
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@agentforge-ai/channels-slack",
3
+ "version": "0.7.0",
4
+ "description": "Slack channel adapter for AgentForge",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md"
17
+ ],
18
+ "dependencies": {
19
+ "@slack/bolt": "^4.1.0",
20
+ "@slack/web-api": "^7.8.0",
21
+ "zod": "^3.22.0"
22
+ },
23
+ "peerDependencies": {
24
+ "@agentforge-ai/core": ">=0.5.0"
25
+ },
26
+ "devDependencies": {
27
+ "tsup": "^8.0.0",
28
+ "typescript": "^5.5.0",
29
+ "vitest": "^2.0.0",
30
+ "@agentforge-ai/core": "0.7.0"
31
+ },
32
+ "keywords": [
33
+ "ai",
34
+ "agents",
35
+ "slack",
36
+ "channels",
37
+ "agentforge"
38
+ ],
39
+ "license": "Apache-2.0",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/Agentic-Engineering-Agency/agentforge.git",
43
+ "directory": "packages/channels-slack"
44
+ },
45
+ "scripts": {
46
+ "build": "tsup",
47
+ "test": "vitest run",
48
+ "typecheck": "tsc --noEmit",
49
+ "clean": "rm -rf dist"
50
+ }
51
+ }