@zhin.js/adapter-slack 4.0.1 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +77 -160
  3. package/adapters/slack.ts +34 -0
  4. package/{skills/slack/SKILL.md → agent/skills/slack.md} +2 -0
  5. package/agent/tools/add_reaction.ts +26 -0
  6. package/agent/tools/archive_channel.ts +24 -0
  7. package/agent/tools/edit_message.ts +28 -0
  8. package/agent/tools/invite_to_channel.ts +26 -0
  9. package/agent/tools/pin_message.ts +26 -0
  10. package/agent/tools/remove_reaction.ts +26 -0
  11. package/agent/tools/set_purpose.ts +26 -0
  12. package/agent/tools/set_topic.ts +26 -0
  13. package/agent/tools/unarchive.ts +24 -0
  14. package/agent/tools/unpin_message.ts +26 -0
  15. package/agent/tools/user_info.ts +31 -0
  16. package/lib/endpoint.d.ts +133 -94
  17. package/lib/endpoint.js +270 -612
  18. package/lib/index.d.ts +11 -10
  19. package/lib/index.js +11 -252
  20. package/lib/markdown-to-mrkdwn.d.ts +9 -0
  21. package/lib/markdown-to-mrkdwn.js +121 -0
  22. package/lib/mrkdwn-to-markdown.d.ts +4 -0
  23. package/lib/mrkdwn-to-markdown.js +30 -0
  24. package/lib/platform-permit.d.ts +1 -2
  25. package/lib/platform-permit.js +4 -2
  26. package/lib/protocol.d.ts +143 -0
  27. package/lib/protocol.js +225 -0
  28. package/lib/slack-agent-deps.d.ts +28 -0
  29. package/lib/slack-agent-deps.js +30 -0
  30. package/lib/slack-inbound-filter.d.ts +12 -0
  31. package/lib/slack-inbound-filter.js +46 -0
  32. package/lib/slack-message-ref.d.ts +7 -0
  33. package/lib/slack-message-ref.js +17 -0
  34. package/lib/slack-outbound.d.ts +24 -0
  35. package/lib/slack-outbound.js +109 -0
  36. package/lib/slack-reaction.d.ts +1 -0
  37. package/lib/slack-reaction.js +26 -0
  38. package/lib/slack-response-url.d.ts +5 -0
  39. package/lib/slack-response-url.js +16 -0
  40. package/lib/webhook.d.ts +14 -0
  41. package/lib/webhook.js +69 -0
  42. package/package.json +53 -14
  43. package/plugin.ts +13 -0
  44. package/schema.json +38 -0
  45. package/src/endpoint.ts +339 -647
  46. package/src/index.ts +65 -277
  47. package/src/markdown-to-mrkdwn.ts +117 -0
  48. package/src/mrkdwn-to-markdown.ts +29 -0
  49. package/src/platform-permit.ts +1 -2
  50. package/src/protocol.ts +380 -0
  51. package/src/slack-agent-deps.ts +57 -0
  52. package/src/slack-inbound-filter.ts +60 -0
  53. package/src/slack-message-ref.ts +18 -0
  54. package/src/slack-outbound.ts +167 -0
  55. package/src/slack-reaction.ts +23 -0
  56. package/src/slack-response-url.ts +26 -0
  57. package/src/webhook.ts +103 -0
  58. package/lib/adapter.d.ts +0 -19
  59. package/lib/adapter.d.ts.map +0 -1
  60. package/lib/adapter.js +0 -46
  61. package/lib/adapter.js.map +0 -1
  62. package/lib/endpoint.d.ts.map +0 -1
  63. package/lib/endpoint.js.map +0 -1
  64. package/lib/index.d.ts.map +0 -1
  65. package/lib/index.js.map +0 -1
  66. package/lib/platform-permit.d.ts.map +0 -1
  67. package/lib/platform-permit.js.map +0 -1
  68. package/lib/segment-mapper.d.ts +0 -2
  69. package/lib/segment-mapper.d.ts.map +0 -1
  70. package/lib/segment-mapper.js +0 -2
  71. package/lib/segment-mapper.js.map +0 -1
  72. package/lib/types.d.ts +0 -17
  73. package/lib/types.d.ts.map +0 -1
  74. package/lib/types.js +0 -2
  75. package/lib/types.js.map +0 -1
  76. package/plugin.yml +0 -3
  77. package/src/adapter.ts +0 -54
  78. package/src/segment-mapper.ts +0 -1
  79. package/src/types.ts +0 -18
  80. /package/{skills/slack → agent}/PERMITS.md +0 -0
@@ -0,0 +1,380 @@
1
+ /**
2
+ * Slack protocol helpers — no legacy Adapter/Endpoint / segment-mapper.
3
+ * Canonicalization is owned by gateway/core before endpoint.send.
4
+ */
5
+ import { createHmac, timingSafeEqual } from 'node:crypto';
6
+ import type { IncomingMessage } from 'node:http';
7
+ import { mrkdwnToMarkdown } from './mrkdwn-to-markdown.js';
8
+
9
+ const SLACK_SIG_VERSION = 'v0';
10
+ const MAX_TIMESTAMP_DRIFT_SECONDS = 300;
11
+
12
+ /** Plugin Runtime owner config (`plugins.<instanceKey>` / schema.json). */
13
+ export interface SlackAdapterConfig {
14
+ readonly name?: string;
15
+ readonly token?: string;
16
+ readonly signingSecret?: string;
17
+ readonly appToken?: string;
18
+ /** Default true (Socket Mode). Set false for HTTP Events API via httpHostToken. */
19
+ readonly socketMode?: boolean;
20
+ readonly webhookPath?: string;
21
+ readonly clientPingTimeout?: number;
22
+ /** Transitional: legacy root `endpoints[]` with `context: slack`. */
23
+ readonly endpoints?: ReadonlyArray<Partial<ResolvedSlackConfig> & {
24
+ readonly context?: string;
25
+ readonly socketMode?: boolean;
26
+ readonly signingSecret?: string;
27
+ readonly appToken?: string;
28
+ readonly webhookPath?: string;
29
+ readonly clientPingTimeout?: number;
30
+ }>;
31
+ }
32
+
33
+ export interface ResolvedSlackConfig {
34
+ readonly context: 'slack';
35
+ readonly name: string;
36
+ readonly token: string;
37
+ readonly mode: 'socket' | 'http';
38
+ readonly signingSecret: string;
39
+ readonly appToken?: string;
40
+ readonly webhookPath: string;
41
+ readonly clientPingTimeout: number;
42
+ }
43
+
44
+ export interface SlackEventEnvelope {
45
+ readonly token?: string;
46
+ readonly team_id?: string;
47
+ readonly api_app_id?: string;
48
+ readonly event: SlackEvent;
49
+ readonly type: 'event_callback';
50
+ readonly event_id?: string;
51
+ readonly event_time?: number;
52
+ }
53
+
54
+ export interface SlackUrlVerification {
55
+ readonly type: 'url_verification';
56
+ readonly token: string;
57
+ readonly challenge: string;
58
+ }
59
+
60
+ export interface SlackInteractionPayload {
61
+ readonly type: 'block_actions' | 'message_action' | 'shortcut' | 'view_submission' | 'view_closed';
62
+ readonly trigger_id?: string;
63
+ readonly user: { id: string; username?: string; name?: string; team_id?: string };
64
+ readonly channel?: { id: string; name?: string };
65
+ readonly message?: { ts: string; text?: string; [key: string]: unknown };
66
+ readonly actions?: SlackBlockAction[];
67
+ readonly response_url?: string;
68
+ readonly [key: string]: unknown;
69
+ }
70
+
71
+ export interface SlackBlockAction {
72
+ readonly type: string;
73
+ readonly action_id: string;
74
+ readonly block_id: string;
75
+ readonly value?: string;
76
+ readonly text?: { type: string; text: string };
77
+ readonly action_ts?: string;
78
+ readonly [key: string]: unknown;
79
+ }
80
+
81
+ export interface SlackSlashCommand {
82
+ readonly token: string;
83
+ readonly team_id: string;
84
+ readonly channel_id: string;
85
+ readonly channel_name: string;
86
+ readonly user_id: string;
87
+ readonly user_name: string;
88
+ readonly command: string;
89
+ readonly text: string;
90
+ readonly response_url: string;
91
+ readonly trigger_id: string;
92
+ readonly api_app_id?: string;
93
+ }
94
+
95
+ export interface SlackEvent {
96
+ readonly type: string;
97
+ readonly ts?: string;
98
+ readonly event_ts?: string;
99
+ readonly user?: string;
100
+ readonly channel?: string;
101
+ readonly channel_type?: string;
102
+ readonly text?: string;
103
+ readonly thread_ts?: string;
104
+ readonly subtype?: string;
105
+ readonly bot_id?: string;
106
+ readonly [key: string]: unknown;
107
+ }
108
+
109
+ export type SlackMessageEvent = SlackEvent & {
110
+ readonly type: 'message' | 'app_mention';
111
+ readonly ts: string;
112
+ readonly channel: string;
113
+ };
114
+
115
+ export interface SlackWireSegment {
116
+ readonly type: string;
117
+ readonly data?: Record<string, unknown>;
118
+ }
119
+
120
+ export function resolveSlackConfig(config: SlackAdapterConfig = {}): ResolvedSlackConfig {
121
+ const entry = config.endpoints?.find((item) => item.context === 'slack');
122
+ const token = config.token
123
+ ?? entry?.token
124
+ ?? process.env.SLACK_BOT_TOKEN
125
+ ?? process.env.SLACK_TOKEN;
126
+ if (!token) {
127
+ throw new TypeError(
128
+ 'Slack adapter requires token (plugins.<key>.token or endpoints with context: slack)',
129
+ );
130
+ }
131
+
132
+ const name = (typeof config.name === 'string' && config.name)
133
+ || (typeof entry?.name === 'string' && entry.name)
134
+ || process.env.SLACK_BOT_NAME
135
+ || 'slack-bot';
136
+
137
+ const socketMode = config.socketMode ?? entry?.socketMode;
138
+ // Prefer Socket Mode (default true) — no public URL required.
139
+ const mode: 'socket' | 'http' = socketMode === false ? 'http' : 'socket';
140
+
141
+ const signingSecret = config.signingSecret
142
+ ?? entry?.signingSecret
143
+ ?? process.env.SLACK_SIGNING_SECRET
144
+ ?? '';
145
+ const appToken = config.appToken
146
+ ?? entry?.appToken
147
+ ?? process.env.SLACK_APP_TOKEN
148
+ ?? undefined;
149
+
150
+ if (mode === 'socket' && !appToken) {
151
+ throw new TypeError(
152
+ 'Slack Socket Mode requires appToken (xapp-...); set socketMode: false for HTTP Events API',
153
+ );
154
+ }
155
+ if (mode === 'http' && !signingSecret) {
156
+ throw new TypeError(
157
+ 'Slack HTTP Events API requires signingSecret',
158
+ );
159
+ }
160
+
161
+ return {
162
+ context: 'slack',
163
+ name,
164
+ token,
165
+ mode,
166
+ signingSecret,
167
+ appToken,
168
+ webhookPath: normalizeWebhookPath(
169
+ config.webhookPath ?? entry?.webhookPath ?? '/slack/events',
170
+ ),
171
+ clientPingTimeout: config.clientPingTimeout
172
+ ?? entry?.clientPingTimeout
173
+ ?? 15_000,
174
+ };
175
+ }
176
+
177
+ export function normalizeWebhookPath(path: string): string {
178
+ const trimmed = path.trim() || '/slack/events';
179
+ return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
180
+ }
181
+
182
+ export function resolveSlackChannelType(event: Pick<SlackEvent, 'channel_type'>): 'private' | 'group' {
183
+ return event.channel_type === 'im' ? 'private' : 'group';
184
+ }
185
+
186
+ /** Build inbound text for MessageGateway.receive. */
187
+ export function formatInboundContent(event: SlackMessageEvent | SlackEvent): string {
188
+ const text = typeof event.text === 'string' ? event.text : '';
189
+ if (text) return mrkdwnToMarkdown(text);
190
+ if ('files' in event && Array.isArray(event.files) && event.files.length > 0) {
191
+ return '[file]';
192
+ }
193
+ return '';
194
+ }
195
+
196
+ export function formatInteractionContent(payload: SlackInteractionPayload): string {
197
+ const action = payload.actions?.[0];
198
+ if (!action) return '[action]';
199
+ const label = action.text?.text ?? action.value ?? action.action_id;
200
+ return `[action: ${action.action_id}${label ? ` ${label}` : ''}]`;
201
+ }
202
+
203
+ export function formatSlashContent(cmd: SlackSlashCommand): string {
204
+ return `${cmd.command} ${cmd.text}`.trim();
205
+ }
206
+
207
+ export function inboundMessageId(event: SlackMessageEvent): string {
208
+ return `${event.channel}:${event.ts}`;
209
+ }
210
+
211
+ /**
212
+ * Wire-encode an already-rendered outbound payload into Slack text + Block Kit blocks.
213
+ * Segment canonicalization is intentionally not done here.
214
+ */
215
+ export function formatOutboundWire(payload: unknown): {
216
+ text: string;
217
+ blocks: Record<string, unknown>[];
218
+ attachments: Record<string, unknown>[];
219
+ files: Array<{ buffer?: Buffer; url?: string; path?: string; name?: string }>;
220
+ } {
221
+ if (typeof payload === 'string') {
222
+ return { text: payload, blocks: [], attachments: [], files: [] };
223
+ }
224
+
225
+ const items: Array<string | SlackWireSegment> = Array.isArray(payload)
226
+ ? payload as Array<string | SlackWireSegment>
227
+ : payload && typeof payload === 'object' && 'type' in (payload as object)
228
+ ? [payload as SlackWireSegment]
229
+ : [];
230
+
231
+ if (items.length === 0) {
232
+ const text = payload == null
233
+ ? ''
234
+ : typeof payload === 'object'
235
+ ? JSON.stringify(payload)
236
+ : String(payload);
237
+ return { text, blocks: [], attachments: [], files: [] };
238
+ }
239
+
240
+ let text = '';
241
+ const blocks: Record<string, unknown>[] = [];
242
+ const attachments: Record<string, unknown>[] = [];
243
+ const files: Array<{ buffer?: Buffer; url?: string; path?: string; name?: string }> = [];
244
+
245
+ for (const item of items) {
246
+ if (typeof item === 'string') {
247
+ text += item;
248
+ continue;
249
+ }
250
+ const data = item.data ?? {};
251
+ switch (item.type) {
252
+ case 'text':
253
+ text += String(data.text ?? data.content ?? '');
254
+ break;
255
+ case 'at':
256
+ case 'mention':
257
+ text += `<@${String(data.id ?? data.target ?? '')}>`;
258
+ break;
259
+ case 'channel_mention':
260
+ text += `<#${String(data.id ?? '')}>`;
261
+ break;
262
+ case 'link':
263
+ if (data.text && data.text !== data.url) {
264
+ text += `<${String(data.url)}|${String(data.text)}>`;
265
+ } else {
266
+ text += `<${String(data.url ?? '')}>`;
267
+ }
268
+ break;
269
+ case 'image':
270
+ if (typeof data.url === 'string' && data.url) {
271
+ attachments.push({
272
+ image_url: data.url,
273
+ title: String(data.name ?? data.title ?? ''),
274
+ });
275
+ } else if (data.media && typeof data.media === 'object') {
276
+ files.push(resolveMediaToFile(data.media as { kind: string; value: string }, String(data.alt ?? 'image')));
277
+ }
278
+ break;
279
+ case 'audio':
280
+ case 'video':
281
+ case 'file':
282
+ if (data.media && typeof data.media === 'object') {
283
+ files.push(resolveMediaToFile(data.media as { kind: string; value: string }, String(data.name ?? item.type)));
284
+ } else if (data.file || data.url) {
285
+ files.push({
286
+ path: typeof data.file === 'string' ? data.file : undefined,
287
+ url: typeof data.url === 'string' ? data.url : undefined,
288
+ name: String(data.name ?? item.type),
289
+ });
290
+ }
291
+ break;
292
+ case 'keyboard':
293
+ blocks.push(...keyboardToBlockKitBlocks(data));
294
+ break;
295
+ default:
296
+ text += String(data.text ?? `[${item.type}]`);
297
+ }
298
+ }
299
+
300
+ return { text, blocks, attachments, files };
301
+ }
302
+
303
+ export function keyboardToBlockKitBlocks(data: Record<string, unknown>): Record<string, unknown>[] {
304
+ const rows = data.rows as Array<Array<Record<string, unknown>>> | undefined;
305
+ if (!rows?.length) return [];
306
+
307
+ const blocks: Record<string, unknown>[] = [];
308
+ for (const row of rows) {
309
+ const elements = row.slice(0, 5).map((btn, index) => ({
310
+ type: 'button',
311
+ text: { type: 'plain_text', text: String(btn.label ?? btn.text ?? 'button').slice(0, 75) },
312
+ action_id: String(btn.id ?? btn.action_id ?? `btn_${blocks.length}_${index}`),
313
+ ...(btn.value != null ? { value: String(btn.value) } : {}),
314
+ ...(btn.style === 'primary' ? { style: 'primary' } : {}),
315
+ ...(btn.style === 'danger' ? { style: 'danger' } : {}),
316
+ }));
317
+ if (elements.length > 0) {
318
+ blocks.push({ type: 'actions', elements });
319
+ }
320
+ }
321
+ return blocks;
322
+ }
323
+
324
+ function resolveMediaToFile(
325
+ media: { kind: string; value: string },
326
+ name: string,
327
+ ): { buffer?: Buffer; url?: string; name: string } {
328
+ if (media.kind === 'base64') {
329
+ return { buffer: Buffer.from(media.value, 'base64'), name };
330
+ }
331
+ return { url: media.value, name };
332
+ }
333
+
334
+ export function verifySlackSignature(
335
+ signingSecret: string,
336
+ rawBody: string,
337
+ timestamp: string,
338
+ signature: string,
339
+ ): boolean {
340
+ const now = Math.floor(Date.now() / 1000);
341
+ const ts = parseInt(timestamp, 10);
342
+ if (Number.isNaN(ts) || Math.abs(now - ts) > MAX_TIMESTAMP_DRIFT_SECONDS) {
343
+ return false;
344
+ }
345
+
346
+ const baseString = `${SLACK_SIG_VERSION}:${timestamp}:${rawBody}`;
347
+ const hmac = createHmac('sha256', signingSecret).update(baseString).digest('hex');
348
+ const expected = `${SLACK_SIG_VERSION}=${hmac}`;
349
+
350
+ if (expected.length !== signature.length) return false;
351
+ return timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
352
+ }
353
+
354
+ export async function readTextBody(
355
+ request: IncomingMessage,
356
+ options: { readonly limit?: number } = {},
357
+ ): Promise<string> {
358
+ const limit = options.limit ?? 1_048_576;
359
+ const chunks: Buffer[] = [];
360
+ let size = 0;
361
+ for await (const chunk of request) {
362
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
363
+ size += buffer.length;
364
+ if (size > limit) {
365
+ request.destroy();
366
+ throw new Error(`Request body exceeds ${limit} bytes`);
367
+ }
368
+ chunks.push(buffer);
369
+ }
370
+ return Buffer.concat(chunks).toString('utf8');
371
+ }
372
+
373
+ export function headerValue(
374
+ headers: IncomingMessage['headers'],
375
+ name: string,
376
+ ): string {
377
+ const raw = headers[name.toLowerCase()];
378
+ if (Array.isArray(raw)) return raw[0] ?? '';
379
+ return raw ?? '';
380
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Agent tool deps for slack.
3
+ * Endpoints register themselves on start; tools look up by config name / endpoint id.
4
+ */
5
+
6
+ export interface SlackAgentEndpoint {
7
+ inviteToChannel(channel: string, users: string[]): Promise<boolean>;
8
+ kickFromChannel(channel: string, user: string): Promise<boolean>;
9
+ setChannelTopic(channel: string, topic: string): Promise<boolean>;
10
+ setChannelPurpose(channel: string, purpose: string): Promise<boolean>;
11
+ archiveChannel(channel: string): Promise<boolean>;
12
+ unarchiveChannel(channel: string): Promise<boolean>;
13
+ renameChannel(channel: string, name: string): Promise<boolean>;
14
+ getChannelMembers(channel: string): Promise<string[]>;
15
+ getChannelInfo(channel: string): Promise<unknown>;
16
+ getUserInfo(user: string): Promise<unknown>;
17
+ addReaction(channel: string, timestamp: string, name: string): Promise<boolean>;
18
+ removeReaction(channel: string, timestamp: string, name: string): Promise<boolean>;
19
+ pinMessage(channel: string, timestamp: string): Promise<boolean>;
20
+ unpinMessage(channel: string, timestamp: string): Promise<boolean>;
21
+ editMessage(channel: string, messageTs: string, content: unknown): Promise<void>;
22
+ }
23
+
24
+ export interface SlackAgentDeps {
25
+ getEndpoint: (endpointId: string) => SlackAgentEndpoint;
26
+ }
27
+
28
+ const endpoints = new Map<string, SlackAgentEndpoint>();
29
+ let override: SlackAgentDeps | null = null;
30
+
31
+ export function registerSlackAgentEndpoint(
32
+ endpointId: string,
33
+ endpoint: SlackAgentEndpoint,
34
+ ): () => void {
35
+ endpoints.set(endpointId, endpoint);
36
+ return () => {
37
+ if (endpoints.get(endpointId) === endpoint) {
38
+ endpoints.delete(endpointId);
39
+ }
40
+ };
41
+ }
42
+
43
+ /** Optional override used by tests / transitional callers. Pass `null` to clear. */
44
+ export function setSlackAgentDeps(deps: SlackAgentDeps | null): void {
45
+ override = deps;
46
+ }
47
+
48
+ export function getSlackAgentDeps(): SlackAgentDeps {
49
+ if (override) return override;
50
+ return {
51
+ getEndpoint(endpointId: string): SlackAgentEndpoint {
52
+ const registered = endpoints.get(endpointId);
53
+ if (!registered) throw new Error(`Endpoint ${endpointId} 不存在`);
54
+ return registered;
55
+ },
56
+ };
57
+ }
@@ -0,0 +1,60 @@
1
+ import type { SlackMessageEvent } from './protocol.js';
2
+
3
+ const DEDUPE_TTL_MS = 60_000;
4
+
5
+ export interface SlackInboundFilterState {
6
+ seenInbound: Map<string, number>;
7
+ }
8
+
9
+ export function createSlackInboundFilterState(): SlackInboundFilterState {
10
+ return { seenInbound: new Map() };
11
+ }
12
+
13
+ function pruneSeen(state: SlackInboundFilterState, now: number): void {
14
+ if (state.seenInbound.size < 512) return;
15
+ for (const [key, at] of state.seenInbound) {
16
+ if (now - at > DEDUPE_TTL_MS) {
17
+ state.seenInbound.delete(key);
18
+ }
19
+ }
20
+ }
21
+
22
+ /**
23
+ * 过滤不应进入 IM 管道的 Slack 入站消息。
24
+ * - 跳过 Bot 自身消息
25
+ * - 频道内 @Bot:只保留 app_mention,丢弃重复的 message 事件
26
+ * - channel:ts 去重(message + app_mention 等同一条)
27
+ */
28
+ export function shouldDropSlackInboundMessage(
29
+ event: SlackMessageEvent,
30
+ state: SlackInboundFilterState,
31
+ botUserId?: string,
32
+ ): boolean {
33
+ if (event.subtype === 'bot_message' || event.subtype === 'message_changed') {
34
+ return true;
35
+ }
36
+
37
+ if (event.bot_id) return true;
38
+ if (botUserId && event.user === botUserId) return true;
39
+
40
+ const channelType = event.channel_type ?? 'channel';
41
+ const text = event.text ?? '';
42
+
43
+ if (event.type === 'message' && channelType !== 'im' && botUserId) {
44
+ if (text.includes(`<@${botUserId}>`)) {
45
+ return true;
46
+ }
47
+ }
48
+
49
+ if (!event.channel || !event.ts) return true;
50
+
51
+ const key = `${event.channel}:${event.ts}`;
52
+ const now = Date.now();
53
+ const seenAt = state.seenInbound.get(key);
54
+ if (seenAt != null && now - seenAt < DEDUPE_TTL_MS) {
55
+ return true;
56
+ }
57
+ state.seenInbound.set(key, now);
58
+ pruneSeen(state, now);
59
+ return false;
60
+ }
@@ -0,0 +1,18 @@
1
+ /** Slack 消息定位:channel + ts(Activity Feedback / recall / reaction 共用) */
2
+
3
+ export function formatSlackMessageRef(channel: string, ts: string): string {
4
+ return `${channel}:${ts}`;
5
+ }
6
+
7
+ export function parseSlackMessageRef(ref: string): { channel: string; ts: string } | null {
8
+ const sep = ref.indexOf(':');
9
+ if (sep <= 0) return null;
10
+ const channel = ref.slice(0, sep);
11
+ const ts = ref.slice(sep + 1);
12
+ if (!channel || !ts) return null;
13
+ return { channel, ts };
14
+ }
15
+
16
+ export function slackMessageTs(ref: string): string {
17
+ return parseSlackMessageRef(ref)?.ts ?? ref;
18
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Slack outbound — chat.postMessage + Block Kit + files.uploadV2
3
+ */
4
+ import type { Logger } from '@zhin.js/logger';
5
+ import { markdownToMrkdwn, mrkdwnToPlainFallback, splitMrkdwnText } from './markdown-to-mrkdwn.js';
6
+ import { formatOutboundWire, keyboardToBlockKitBlocks } from './protocol.js';
7
+
8
+ export interface SlackOutboundResult {
9
+ ts: string;
10
+ }
11
+
12
+ export interface SlackSendOptions {
13
+ channel: string;
14
+ threadTs?: string;
15
+ }
16
+
17
+ export interface SlackChatClient {
18
+ chat: {
19
+ postMessage(opts: Record<string, unknown>): Promise<{ ts?: string }>;
20
+ update(opts: Record<string, unknown>): Promise<unknown>;
21
+ };
22
+ filesUploadV2?(opts: Record<string, unknown>): Promise<unknown>;
23
+ }
24
+
25
+ const SLACK_MAX_BLOCKS_PER_MESSAGE = 48;
26
+
27
+ export async function sendSlackContent(
28
+ client: SlackChatClient,
29
+ content: unknown,
30
+ opts: SlackSendOptions,
31
+ logger: Logger,
32
+ ): Promise<SlackOutboundResult> {
33
+ const wire = formatOutboundWire(content);
34
+ const blocks = [...wire.blocks];
35
+ const textDelivery = applyTextMrkdwnBlocks(wire.text, blocks);
36
+
37
+ for (const pf of wire.files) {
38
+ try {
39
+ await uploadFile(client, opts.channel, pf, opts.threadTs, logger);
40
+ } catch (e) {
41
+ logger.error('Failed to upload file:', e);
42
+ }
43
+ }
44
+
45
+ return postSlackMessage(client, {
46
+ channel: opts.channel,
47
+ threadTs: opts.threadTs,
48
+ blocks,
49
+ attachments: wire.attachments,
50
+ fallbackText: textDelivery.fallbackText,
51
+ });
52
+ }
53
+
54
+ export async function editSlackContent(
55
+ client: SlackChatClient,
56
+ channel: string,
57
+ ts: string,
58
+ content: unknown,
59
+ ): Promise<void> {
60
+ const wire = formatOutboundWire(content);
61
+ const blocks = [...wire.blocks];
62
+ const textDelivery = applyTextMrkdwnBlocks(wire.text, blocks);
63
+ const payloadBlocks = blocks.slice(0, SLACK_MAX_BLOCKS_PER_MESSAGE);
64
+
65
+ const updateOpts: Record<string, unknown> = {
66
+ channel,
67
+ ts,
68
+ text: textDelivery.fallbackText || ' ',
69
+ };
70
+ if (payloadBlocks.length > 0) updateOpts.blocks = payloadBlocks;
71
+ await client.chat.update(updateOpts);
72
+ }
73
+
74
+ function applyTextMrkdwnBlocks(
75
+ textContent: string,
76
+ blocks: Record<string, unknown>[],
77
+ ): { fallbackText: string } {
78
+ const trimmed = textContent.trim();
79
+ if (!trimmed) return { fallbackText: '' };
80
+
81
+ const mrkdwn = markdownToMrkdwn(trimmed);
82
+ const sections = splitMrkdwnText(mrkdwn).map((chunk) => ({
83
+ type: 'section',
84
+ text: { type: 'mrkdwn', text: chunk },
85
+ }));
86
+
87
+ if (blocks.length > 0) {
88
+ blocks.unshift(...sections);
89
+ return { fallbackText: '' };
90
+ }
91
+ blocks.push(...sections);
92
+ return { fallbackText: mrkdwnToPlainFallback(mrkdwn) };
93
+ }
94
+
95
+ async function postSlackMessage(
96
+ client: SlackChatClient,
97
+ opts: {
98
+ channel: string;
99
+ threadTs?: string;
100
+ blocks: Record<string, unknown>[];
101
+ attachments: Record<string, unknown>[];
102
+ fallbackText: string;
103
+ },
104
+ ): Promise<SlackOutboundResult> {
105
+ const { channel, blocks, attachments, fallbackText } = opts;
106
+ let threadTs = opts.threadTs;
107
+ let firstTs = '';
108
+
109
+ if (blocks.length === 0) {
110
+ const result = await client.chat.postMessage({
111
+ channel,
112
+ text: fallbackText || 'Message',
113
+ ...(threadTs ? { thread_ts: threadTs } : {}),
114
+ ...(attachments.length > 0 ? { attachments } : {}),
115
+ });
116
+ return { ts: result.ts ?? '' };
117
+ }
118
+
119
+ for (let offset = 0; offset < blocks.length; offset += SLACK_MAX_BLOCKS_PER_MESSAGE) {
120
+ const chunk = blocks.slice(offset, offset + SLACK_MAX_BLOCKS_PER_MESSAGE);
121
+ const result = await client.chat.postMessage({
122
+ channel,
123
+ text: offset === 0 ? (fallbackText || ' ') : ' ',
124
+ blocks: chunk,
125
+ ...(threadTs ? { thread_ts: threadTs } : {}),
126
+ ...(offset === 0 && attachments.length > 0 ? { attachments } : {}),
127
+ });
128
+ const ts = result.ts ?? '';
129
+ if (!firstTs) firstTs = ts;
130
+ if (!threadTs) threadTs = ts;
131
+ }
132
+
133
+ return { ts: firstTs };
134
+ }
135
+
136
+ async function uploadFile(
137
+ client: SlackChatClient,
138
+ channel: string,
139
+ file: { buffer?: Buffer; url?: string; path?: string; name?: string },
140
+ threadTs?: string,
141
+ logger?: Logger,
142
+ ): Promise<void> {
143
+ if (!client.filesUploadV2) return;
144
+ try {
145
+ let buffer = file.buffer;
146
+ if (!buffer && file.path) {
147
+ const { readFile } = await import('node:fs/promises');
148
+ buffer = await readFile(file.path);
149
+ }
150
+ if (!buffer && file.url) {
151
+ const res = await fetch(file.url);
152
+ if (!res.ok) throw new Error(`fetch ${file.url}: ${res.status}`);
153
+ buffer = Buffer.from(await res.arrayBuffer());
154
+ }
155
+ if (!buffer) return;
156
+
157
+ await client.filesUploadV2(
158
+ threadTs
159
+ ? { channel_id: channel, file: buffer, filename: file.name ?? 'file', thread_ts: threadTs }
160
+ : { channel_id: channel, file: buffer, filename: file.name ?? 'file' },
161
+ );
162
+ } catch (e) {
163
+ logger?.error('File upload failed:', e);
164
+ }
165
+ }
166
+
167
+ export { keyboardToBlockKitBlocks };
@@ -0,0 +1,23 @@
1
+ /** 将 activity-feedback / 工具入参规范为 Slack reactions.add 的 name(不含冒号) */
2
+ const UNICODE_TO_SLACK: Record<string, string> = {
3
+ '⏳': 'hourglass_flowing_sand',
4
+ '✅': 'white_check_mark',
5
+ '❌': 'x',
6
+ '⏰': 'alarm_clock',
7
+ '🤔': 'thinking_face',
8
+ '👀': 'eyes',
9
+ };
10
+
11
+ export function normalizeSlackReactionName(emoji: string): string {
12
+ const trimmed = emoji.trim();
13
+ if (!trimmed) return 'hourglass_flowing_sand';
14
+ if (UNICODE_TO_SLACK[trimmed]) return UNICODE_TO_SLACK[trimmed]!;
15
+ if (trimmed.startsWith(':') && trimmed.endsWith(':') && trimmed.length > 2) {
16
+ return trimmed.slice(1, -1);
17
+ }
18
+ let start = 0;
19
+ let end = trimmed.length;
20
+ while (start < end && trimmed[start] === ':') start++;
21
+ while (end > start && trimmed[end - 1] === ':') end--;
22
+ return trimmed.slice(start, end);
23
+ }