@kadaliao/dsh-bots 0.3.3 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +142 -4
- package/README.zh-CN.md +119 -3
- package/client.js +564 -43
- package/index.js +186 -25
- package/lib/apps.mjs +150 -5
- package/lib/channels/discord.mjs +590 -0
- package/lib/channels/feishu.mjs +1249 -0
- package/lib/channels/slack.mjs +906 -0
- package/lib/channels/telegram.mjs +300 -0
- package/lib/channels.mjs +893 -0
- package/lib/logos.mjs +54 -0
- package/lib/prompt.mjs +9 -1
- package/lib/skills.mjs +199 -6
- package/lib/store.mjs +22 -3
- package/logos/amap.png +0 -0
- package/logos/anthropic.png +0 -0
- package/logos/baidu-map.png +0 -0
- package/logos/brave.png +0 -0
- package/logos/context7.png +0 -0
- package/logos/discord.png +0 -0
- package/logos/exa.png +0 -0
- package/logos/feishu.png +0 -0
- package/logos/firecrawl.png +0 -0
- package/logos/git.png +0 -0
- package/logos/github.png +0 -0
- package/logos/hubspot.png +0 -0
- package/logos/mcp.png +0 -0
- package/logos/notion.png +0 -0
- package/logos/playwright.png +0 -0
- package/logos/postgres.png +0 -0
- package/logos/sentry.png +0 -0
- package/logos/slack.png +0 -0
- package/logos/sqlite.png +0 -0
- package/logos/stripe.png +0 -0
- package/logos/supabase.png +0 -0
- package/logos/tavily.png +0 -0
- package/logos/telegram.png +0 -0
- package/package.json +3 -1
|
@@ -0,0 +1,906 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slack transport for bot chat channels, over Socket Mode: Slack pushes events
|
|
3
|
+
* down a WebSocket the connector opens, so the computer running the Harness
|
|
4
|
+
* needs no public URL. Replies and lookups go through the Web API.
|
|
5
|
+
*
|
|
6
|
+
* Transport only: it knows nothing about bots, pairing or the store
|
|
7
|
+
* (lib/channels.mjs decides what a message means).
|
|
8
|
+
*
|
|
9
|
+
* - Two tokens: the bot token (`xoxb-…`, `values.token`) for the Web API and
|
|
10
|
+
* the app-level token (`xapp-…`, `values.appToken`, scope connections:write)
|
|
11
|
+
* for `apps.connections.open`, which hands out a short-lived wss URL.
|
|
12
|
+
* - Every envelope is acknowledged with its `envelope_id` as soon as it
|
|
13
|
+
* arrives. A `disconnect` (warning / refresh_requested) opens a replacement
|
|
14
|
+
* socket first and closes the old one once the new one says hello, so no
|
|
15
|
+
* event falls in a gap; `link_disabled` (Socket Mode turned off) is fatal.
|
|
16
|
+
* - Dropped connections reconnect with backoff (1 s … 60 s). Slack pings the
|
|
17
|
+
* socket; when the runtime reports those pings and they stop for a minute
|
|
18
|
+
* (a dead link, a laptop waking up), the connector reconnects.
|
|
19
|
+
* - DMs arrive as `message` events (`channel_type: 'im'`), channel mentions as
|
|
20
|
+
* `app_mention`; one message seen as both is handled once. Bots, the app
|
|
21
|
+
* itself, edits and other subtypes are dropped.
|
|
22
|
+
* - Replies go out as a `markdown` block (Slack renders the Markdown models
|
|
23
|
+
* write, tables and code included) with a plain `text` fallback for
|
|
24
|
+
* notifications and screen readers. In a channel they go to the thread of
|
|
25
|
+
* the message they answer.
|
|
26
|
+
* - No secret appears in a log line, an error or a status.
|
|
27
|
+
*
|
|
28
|
+
* `apiBase` defaults to `BOTS_SLACK_API` or https://slack.com/api, so a local
|
|
29
|
+
* stand-in can be used for testing.
|
|
30
|
+
*
|
|
31
|
+
* @module @kadaliao/dsh-bots/lib/channels/slack
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
import { channel as diagnosticsChannel } from 'node:diagnostics_channel';
|
|
35
|
+
|
|
36
|
+
import { redact, toPlainText } from '../channels.mjs';
|
|
37
|
+
import { backoffDelay, splitMessage } from './discord.mjs';
|
|
38
|
+
|
|
39
|
+
export const kind = 'slack';
|
|
40
|
+
/** What one `send` takes; it posts that as messages of at most PART_LIMIT, all in the same thread. */
|
|
41
|
+
export const TEXT_LIMIT = 40_000;
|
|
42
|
+
/** Replies are Markdown: Slack's `markdown` block renders it. */
|
|
43
|
+
export const MARKDOWN = true;
|
|
44
|
+
/** Replies in a channel go into the thread of the message they answer, every part of them. */
|
|
45
|
+
export const THREADS = true;
|
|
46
|
+
|
|
47
|
+
/** Slack caps the `markdown` blocks of one message at 12,000 characters in all. */
|
|
48
|
+
const PART_LIMIT = 11_000;
|
|
49
|
+
const DEFAULT_API = 'https://slack.com/api';
|
|
50
|
+
const HELLO_TIMEOUT_MS = 15_000;
|
|
51
|
+
/** Slack pings every few seconds; this long without one means the link is dead. */
|
|
52
|
+
const PING_TIMEOUT_MS = 60_000;
|
|
53
|
+
/** Another program may share the app: confirm with a fresh connection after this long, then re-check now and then. */
|
|
54
|
+
const CONFLICT_CHECK_MS = 2 * 60_000;
|
|
55
|
+
const CONFLICT_RECHECK_MS = 10 * 60_000;
|
|
56
|
+
const RATE_LIMIT_RETRIES = 4;
|
|
57
|
+
const MAX_RETRY_WAIT = 60_000;
|
|
58
|
+
/** The "is thinking…" status lasts two minutes unless a reply clears it; refresh it this often. */
|
|
59
|
+
const STATUS_EVERY_MS = 45_000;
|
|
60
|
+
const NAME_TTL_MS = 6 * 3600_000;
|
|
61
|
+
|
|
62
|
+
/** Bot token scopes the app needs: what the manifest asks for. */
|
|
63
|
+
export const BOT_SCOPES = ['app_mentions:read', 'channels:read', 'chat:write', 'groups:read', 'im:history', 'users:read'];
|
|
64
|
+
/** Without these nothing works: no mentions, no replies, no DMs. The rest only name people and channels. */
|
|
65
|
+
const REQUIRED_SCOPES = ['app_mentions:read', 'chat:write', 'im:history'];
|
|
66
|
+
export const BOT_EVENTS = ['app_mention', 'message.im'];
|
|
67
|
+
|
|
68
|
+
const BOT_TOKEN_REJECTED = "Slack rejected the bot token. Copy the Bot User OAuth Token (xoxb-…) again from your app's OAuth & Permissions page; if the app was removed from the workspace, install it again.";
|
|
69
|
+
const APP_TOKEN_REJECTED = 'Slack rejected the app-level token. In your app open Basic Information → App-Level Tokens, generate a token with the connections:write scope and paste it (xapp-…).';
|
|
70
|
+
const APP_TOKEN_SCOPE = 'The app-level token lacks the connections:write scope. In your app open Basic Information → App-Level Tokens, generate a token with connections:write and paste it.';
|
|
71
|
+
const APP_TOKEN_KIND = "The App-level token field must hold an app-level token (xapp-…) from Basic Information → App-Level Tokens, not the bot token.";
|
|
72
|
+
const BOT_TOKEN_KIND = "The Bot token field must hold the Bot User OAuth Token (xoxb-…) from your app's OAuth & Permissions page.";
|
|
73
|
+
const SOCKET_MODE_OFF = 'Socket Mode is off for this Slack app. Turn it on (your app → Socket Mode → Enable Socket Mode), then reconnect.';
|
|
74
|
+
const WS_TROUBLE = '. If this keeps happening, check that Socket Mode is on for the app and that this network allows WebSockets';
|
|
75
|
+
|
|
76
|
+
const BOT_AUTH_ERRORS = new Set(['invalid_auth', 'not_authed', 'token_revoked', 'token_expired', 'account_inactive', 'user_removed_from_team', 'team_disabled']);
|
|
77
|
+
const BLOCK_ERRORS = new Set(['invalid_blocks', 'invalid_blocks_format', 'msg_blocks_too_long']);
|
|
78
|
+
const STATUS_UNSUPPORTED = new Set(['missing_scope', 'method_not_supported_for_channel_type', 'not_allowed_token_type', 'unknown_method', 'method_deprecated', 'deprecated_endpoint', 'no_permission']);
|
|
79
|
+
/** Message subtypes that are a person writing (a file with a caption, a reply also sent to the channel, /me). */
|
|
80
|
+
const HUMAN_SUBTYPES = new Set(['file_share', 'thread_broadcast', 'me_message']);
|
|
81
|
+
const TOKEN_SHAPES = /\b(?:xox[a-z]|xapp|xoxe)(?:\.xox[a-z])?-[A-Za-z0-9-]{6,}/g;
|
|
82
|
+
|
|
83
|
+
/** Bot user id → {teamId, appId} of running connectors, for `links`. */
|
|
84
|
+
const APPS = new Map();
|
|
85
|
+
|
|
86
|
+
const escapeRe = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
87
|
+
const cleanName = (s) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, 80);
|
|
88
|
+
|
|
89
|
+
function remember(map, key, value, max) {
|
|
90
|
+
map.delete(key);
|
|
91
|
+
map.set(key, value);
|
|
92
|
+
if (map.size > max) map.delete(map.keys().next().value);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** A Slack `ts` ("1700000000.000100") as a decimal string that rises with it: the hub's replay guard. */
|
|
96
|
+
export function orderOf(ts) {
|
|
97
|
+
const m = /^(\d{1,20})(?:\.(\d{1,9}))?$/.exec(String(ts ?? ''));
|
|
98
|
+
if (!m) return '';
|
|
99
|
+
return `${m[1]}${(m[2] ?? '').padEnd(6, '0').slice(0, 6)}`.replace(/^0+(?=\d)/, '');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Required scopes missing from an `X-OAuth-Scopes` header ([] when the header is absent). */
|
|
103
|
+
export function missingScopes(header, wanted = REQUIRED_SCOPES) {
|
|
104
|
+
if (typeof header !== 'string' || !header.trim()) return [];
|
|
105
|
+
const have = header.split(',').map((s) => s.trim()).filter(Boolean);
|
|
106
|
+
return wanted.filter((w) => !have.some((h) => h === w || h.startsWith(`${w}:`)));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Why these two strings cannot be a Slack bot token and app-level token, or ''. */
|
|
110
|
+
export function tokenProblem(botToken, appToken) {
|
|
111
|
+
const bot = String(botToken ?? '').trim();
|
|
112
|
+
const app = String(appToken ?? '').trim();
|
|
113
|
+
if (/^xapp-/i.test(bot) && /^xox/i.test(app)) return 'The two Slack tokens are swapped: the Bot token starts with xoxb-, the App-level token with xapp-.';
|
|
114
|
+
if (/^xapp-/i.test(bot)) return `The Bot token field holds an app-level token (xapp-…). ${BOT_TOKEN_KIND}`;
|
|
115
|
+
if (/^xoxp-/i.test(bot)) return `That is a user token (xoxp-…). ${BOT_TOKEN_KIND}`;
|
|
116
|
+
if (/^xox[a-z]-/i.test(app)) return APP_TOKEN_KIND;
|
|
117
|
+
return '';
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Slack message text as plain chat text: the bot's own mention removed, other
|
|
122
|
+
* mentions, channels and links readable, `<` and friends decoded.
|
|
123
|
+
* @param {string} text
|
|
124
|
+
* @param {{botUserId?: string, names?: Map<string, string>}} [ctx] names of mentioned users
|
|
125
|
+
*/
|
|
126
|
+
export function fromSlack(text, { botUserId = '', names } = {}) {
|
|
127
|
+
let s = String(text ?? '');
|
|
128
|
+
if (botUserId) {
|
|
129
|
+
s = s
|
|
130
|
+
.replace(new RegExp(`<@${escapeRe(botUserId)}(?:\\|[^>]*)?>`, 'g'), '\u0000')
|
|
131
|
+
.replace(/[ \t]*\u0000[ \t]*(?=[,,.。!?!?::;;])/g, '')
|
|
132
|
+
.replace(/[ \t]*\u0000[ \t]*/g, ' ');
|
|
133
|
+
}
|
|
134
|
+
s = s
|
|
135
|
+
.replace(/<@([UW][A-Z0-9]+)(?:\|([^>]*))?>/g, (_, id, label) => `@${names?.get?.(id) || label || id}`)
|
|
136
|
+
.replace(/<#([CG][A-Z0-9]+)(?:\|([^>]*))?>/g, (_, id, label) => `#${label || id}`)
|
|
137
|
+
.replace(/<!subteam\^[A-Z0-9]+(?:\|([^>]*))?>/g, (_, label) => label || '@group')
|
|
138
|
+
.replace(/<!date\^[^|>]*\|([^>]*)>/g, '$1')
|
|
139
|
+
.replace(/<!([a-z]+)(?:\|([^>]*))?>/g, (_, k, label) => label || `@${k}`)
|
|
140
|
+
.replace(/<((?:https?|mailto|tel|ftp):[^|>\s]+)\|([^>]+)>/g, (_, url, label) => {
|
|
141
|
+
const bare = url.replace(/^(?:mailto|tel):/, '');
|
|
142
|
+
return label === url || label === bare ? bare : `${label} (${url})`;
|
|
143
|
+
})
|
|
144
|
+
.replace(/<((?:https?|mailto|tel|ftp):[^|>\s]+)>/g, (_, url) => url.replace(/^(?:mailto|tel):/, ''))
|
|
145
|
+
.replace(/</g, '<')
|
|
146
|
+
.replace(/>/g, '>')
|
|
147
|
+
.replace(/&/g, '&');
|
|
148
|
+
return s.replace(/^[ \t,,::;;]+/, '').trim();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Outgoing Markdown with Slack's broadcast mentions (`<!channel>`, `<!here>`, user groups) made plain text: no reply pings a whole channel. */
|
|
152
|
+
export function defuse(md) {
|
|
153
|
+
return String(md ?? '')
|
|
154
|
+
.replace(/<!(here|channel|everyone)(?:\|[^>]*)?>/g, '@$1')
|
|
155
|
+
.replace(/<!subteam\^[A-Z0-9]+(?:\|([^>]*))?>/g, (_, label) => label || '@group');
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The plain `text` of a reply: Markdown markers dropped, Slack's control characters escaped (a user mention stays a mention). */
|
|
159
|
+
export function fallbackText(md) {
|
|
160
|
+
const plain = toPlainText(defuse(md))
|
|
161
|
+
.replace(/&/g, '&')
|
|
162
|
+
.replace(/</g, '<')
|
|
163
|
+
.replace(/>/g, '>')
|
|
164
|
+
.replace(/<@([UW][A-Z0-9]+)>/g, '<@$1>');
|
|
165
|
+
return plain || ' ';
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* An Events API `message` / `app_mention` event as the start of a channel
|
|
170
|
+
* message, or null when it is not a person writing to the bot. `raw` is still
|
|
171
|
+
* Slack-formatted; `thread` is the thread a reply belongs in.
|
|
172
|
+
* @param {object} ev
|
|
173
|
+
* @param {{userId: string, botId?: string}} me
|
|
174
|
+
*/
|
|
175
|
+
export function normalizeEvent(ev, me) {
|
|
176
|
+
if (!ev || typeof ev !== 'object' || !me?.userId) return null;
|
|
177
|
+
if (ev.type !== 'message' && ev.type !== 'app_mention') return null;
|
|
178
|
+
if (ev.subtype != null && ev.subtype !== '' && !HUMAN_SUBTYPES.has(ev.subtype)) return null;
|
|
179
|
+
if (ev.hidden || ev.bot_id || ev.bot_profile || !ev.user) return null;
|
|
180
|
+
if (String(ev.user) === me.userId) return null;
|
|
181
|
+
const chatId = String(ev.channel ?? '');
|
|
182
|
+
const ts = String(ev.ts ?? '');
|
|
183
|
+
const order = orderOf(ts);
|
|
184
|
+
if (!chatId || !order) return null;
|
|
185
|
+
const raw = typeof ev.text === 'string' ? ev.text : '';
|
|
186
|
+
if (!raw.trim()) return null;
|
|
187
|
+
const isDirect = ev.type === 'message' ? ev.channel_type === 'im' : chatId.startsWith('D');
|
|
188
|
+
const mentioned =
|
|
189
|
+
isDirect ||
|
|
190
|
+
ev.type === 'app_mention' ||
|
|
191
|
+
new RegExp(`<@${escapeRe(me.userId)}(?:\\|[^>]*)?>`).test(raw) ||
|
|
192
|
+
(Boolean(ev.parent_user_id) && String(ev.parent_user_id) === me.userId);
|
|
193
|
+
const profile = ev.user_profile ?? {};
|
|
194
|
+
return {
|
|
195
|
+
chatId,
|
|
196
|
+
messageId: ts,
|
|
197
|
+
order,
|
|
198
|
+
userId: String(ev.user),
|
|
199
|
+
raw,
|
|
200
|
+
isDirect,
|
|
201
|
+
mentioned,
|
|
202
|
+
thread: String(ev.thread_ts || ts),
|
|
203
|
+
profileName: cleanName(profile.display_name || profile.real_name || profile.name || ''),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* A link the panel offers next to the pairing code: it opens the app's DM in
|
|
209
|
+
* Slack. Known once the connector has connected in this process.
|
|
210
|
+
*/
|
|
211
|
+
export function links({ account } = {}) {
|
|
212
|
+
const a = APPS.get(String(account?.id ?? ''));
|
|
213
|
+
if (!a?.appId) return {};
|
|
214
|
+
return { link: `https://slack.com/app_redirect?app=${encodeURIComponent(a.appId)}${a.teamId ? `&team=${encodeURIComponent(a.teamId)}` : ''}` };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The app manifest for "Create New App → From a manifest": Socket Mode on, the
|
|
219
|
+
* Messages tab open for DMs, the bot scopes and events the connector uses.
|
|
220
|
+
* @param {{name?: string, description?: string}} [opts]
|
|
221
|
+
*/
|
|
222
|
+
export function appManifest({ name = 'Bot Team', description = 'Message your bot team from Slack: DM the app, or @mention it in a channel.' } = {}) {
|
|
223
|
+
const n = cleanName(name).slice(0, 35) || 'Bot Team';
|
|
224
|
+
return {
|
|
225
|
+
display_information: { name: n, description: cleanName(description).slice(0, 140), background_color: '#4a154b' },
|
|
226
|
+
features: {
|
|
227
|
+
app_home: { home_tab_enabled: false, messages_tab_enabled: true, messages_tab_read_only_enabled: false },
|
|
228
|
+
bot_user: { display_name: n, always_online: true },
|
|
229
|
+
},
|
|
230
|
+
oauth_config: { scopes: { bot: [...BOT_SCOPES] } },
|
|
231
|
+
settings: {
|
|
232
|
+
event_subscriptions: { bot_events: [...BOT_EVENTS] },
|
|
233
|
+
org_deploy_enabled: false,
|
|
234
|
+
socket_mode_enabled: true,
|
|
235
|
+
token_rotation_enabled: false,
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function readJson(res) {
|
|
241
|
+
try {
|
|
242
|
+
const t = await res.text();
|
|
243
|
+
return t ? JSON.parse(t) : null;
|
|
244
|
+
} catch {
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function retryAfterMs(headers) {
|
|
250
|
+
const sec = Number(headers?.get?.('retry-after'));
|
|
251
|
+
return Number.isFinite(sec) && sec >= 0 ? Math.min(MAX_RETRY_WAIT, Math.max(1000, Math.ceil(sec * 1000))) : 1000;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* @typedef {object} ChannelMessage
|
|
256
|
+
* @property {string} chatId the conversation: D… for a DM, C…/G… for a channel
|
|
257
|
+
* @property {string} messageId the message `ts`
|
|
258
|
+
* @property {string} order `ts` as a rising decimal string
|
|
259
|
+
* @property {string} userId
|
|
260
|
+
* @property {string} userName
|
|
261
|
+
* @property {string} text the bot's own mention removed, trimmed
|
|
262
|
+
* @property {boolean} isDirect a DM with the app
|
|
263
|
+
* @property {boolean} mentioned @mentioned; always true in a DM
|
|
264
|
+
* @property {string} [chatTitle] `Workspace #channel`, when Slack names it
|
|
265
|
+
*/
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* @param {object} opts
|
|
269
|
+
* @param {string} [opts.token] the bot token (else `values.token`)
|
|
270
|
+
* @param {{token?: string, appToken?: string}} [opts.values] the app's fields
|
|
271
|
+
* @param {(msg: ChannelMessage) => void} opts.onMessage
|
|
272
|
+
* @param {(s: {state: 'connecting'|'connected'|'error'|'stopped', detail?: string, hint?: string, fatal?: boolean}) => void} [opts.onStatus]
|
|
273
|
+
* @param {(line: string) => void} [opts.log]
|
|
274
|
+
* @param {typeof fetch} [opts.fetchImpl]
|
|
275
|
+
* @param {typeof WebSocket} [opts.WebSocketImpl]
|
|
276
|
+
* @param {string} [opts.apiBase]
|
|
277
|
+
* @param {{subscribe: Function, unsubscribe: Function} | null} [opts.pingChannel] where the runtime reports WebSocket pings; null turns the watchdog off
|
|
278
|
+
* @param {typeof setTimeout} [opts.setTimeoutImpl] for tests
|
|
279
|
+
* @param {typeof clearTimeout} [opts.clearTimeoutImpl] for tests
|
|
280
|
+
* @param {() => number} [opts.now] for tests
|
|
281
|
+
* @param {() => number} [opts.random] for tests (backoff jitter)
|
|
282
|
+
*/
|
|
283
|
+
export function createConnector(opts = {}) {
|
|
284
|
+
const values = opts.values ?? {};
|
|
285
|
+
const botToken = String(opts.token || values.token || '').trim();
|
|
286
|
+
const appToken = String(values.appToken || opts.appToken || '').trim();
|
|
287
|
+
const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
|
|
288
|
+
const WebSocketImpl = opts.WebSocketImpl ?? globalThis.WebSocket;
|
|
289
|
+
const base = String(opts.apiBase || process.env.BOTS_SLACK_API || DEFAULT_API).replace(/\/+$/, '');
|
|
290
|
+
const onMessage = typeof opts.onMessage === 'function' ? opts.onMessage : () => {};
|
|
291
|
+
const setT = opts.setTimeoutImpl ?? setTimeout;
|
|
292
|
+
const clearT = opts.clearTimeoutImpl ?? clearTimeout;
|
|
293
|
+
const now = opts.now ?? Date.now;
|
|
294
|
+
const random = opts.random ?? Math.random;
|
|
295
|
+
let pings = null;
|
|
296
|
+
try {
|
|
297
|
+
pings = opts.pingChannel === undefined ? diagnosticsChannel('undici:websocket:ping') : opts.pingChannel;
|
|
298
|
+
} catch {
|
|
299
|
+
pings = null;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** No string leaves this module with a token (or a connection ticket) in it. */
|
|
303
|
+
const scrub = (v) =>
|
|
304
|
+
redact(String(v ?? ''), [botToken, appToken])
|
|
305
|
+
.replace(TOKEN_SHAPES, '<token>')
|
|
306
|
+
.replace(/ticket=[^&\s"']+/g, 'ticket=<redacted>');
|
|
307
|
+
const log = (line) => {
|
|
308
|
+
try {
|
|
309
|
+
opts.log?.(scrub(line));
|
|
310
|
+
} catch {
|
|
311
|
+
// Logging is a convenience.
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
const status = (state, detail = '', extra = {}) => {
|
|
315
|
+
const s = { state };
|
|
316
|
+
if (detail) s.detail = scrub(detail);
|
|
317
|
+
if (extra.hint) s.hint = extra.hint;
|
|
318
|
+
if (state === 'error') s.fatal = Boolean(extra.fatal);
|
|
319
|
+
try {
|
|
320
|
+
opts.onStatus?.(s);
|
|
321
|
+
} catch (e) {
|
|
322
|
+
log(`slack: onStatus threw: ${e?.message ?? e}`);
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
const guard = (fn) => (...args) => {
|
|
326
|
+
try {
|
|
327
|
+
fn(...args);
|
|
328
|
+
} catch (e) {
|
|
329
|
+
log(`slack: ${e?.message ?? e}`);
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
const cancel = (h) => {
|
|
333
|
+
if (h != null) clearT(h);
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
let stopped = false;
|
|
337
|
+
let dead = false;
|
|
338
|
+
const halted = () => stopped || dead;
|
|
339
|
+
const halt = new AbortController();
|
|
340
|
+
const stoppedError = () => new Error('Slack connector stopped');
|
|
341
|
+
|
|
342
|
+
const sleepers = new Set();
|
|
343
|
+
const sleep = (ms) =>
|
|
344
|
+
new Promise((resolve, reject) => {
|
|
345
|
+
if (halted()) return reject(stoppedError());
|
|
346
|
+
const entry = { reject };
|
|
347
|
+
entry.timer = setT(() => {
|
|
348
|
+
sleepers.delete(entry);
|
|
349
|
+
resolve();
|
|
350
|
+
}, ms);
|
|
351
|
+
sleepers.add(entry);
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
// --- Web API ---------------------------------------------------------------------------
|
|
355
|
+
|
|
356
|
+
/** One Web API call: `{data, headers}`. Errors carry `code` (Slack's `error`), `status` and `needed`. */
|
|
357
|
+
async function call(method, params = {}, { token = botToken, timeoutMs = 15_000, retries = RATE_LIMIT_RETRIES } = {}) {
|
|
358
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
359
|
+
if (stopped) throw stoppedError();
|
|
360
|
+
const signal = AbortSignal.any([halt.signal, AbortSignal.timeout(timeoutMs)]);
|
|
361
|
+
const form = new URLSearchParams();
|
|
362
|
+
for (const [k, v] of Object.entries(params ?? {})) if (v !== undefined && v !== null) form.set(k, typeof v === 'string' ? v : JSON.stringify(v));
|
|
363
|
+
let res;
|
|
364
|
+
let data;
|
|
365
|
+
try {
|
|
366
|
+
res = await fetchImpl(`${base}/${method}`, {
|
|
367
|
+
method: 'POST',
|
|
368
|
+
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
|
|
369
|
+
body: form.toString(),
|
|
370
|
+
signal,
|
|
371
|
+
});
|
|
372
|
+
data = await readJson(res);
|
|
373
|
+
} catch (error) {
|
|
374
|
+
if (stopped) throw stoppedError();
|
|
375
|
+
const why = error?.name === 'TimeoutError' || signal.reason?.name === 'TimeoutError' ? 'timed out' : error?.cause?.code ?? error?.cause?.message ?? error?.message ?? 'network error';
|
|
376
|
+
throw Object.assign(new Error(scrub(`could not reach Slack (${method}: ${why})`)), { network: true });
|
|
377
|
+
}
|
|
378
|
+
const limited = res.status === 429 || data?.error === 'ratelimited' || data?.error === 'rate_limited';
|
|
379
|
+
if (limited && attempt < retries) {
|
|
380
|
+
const wait = retryAfterMs(res.headers);
|
|
381
|
+
log(`slack: rate limited on ${method}, retrying in ${wait} ms`);
|
|
382
|
+
await sleep(wait);
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
if (data?.ok === true) return { data, headers: res.headers };
|
|
386
|
+
const code = String(data?.error || `HTTP ${res.status}`);
|
|
387
|
+
const err = new Error(scrub(`Slack ${method}: ${code}${data?.needed ? ` (needs ${data.needed})` : ''}`));
|
|
388
|
+
err.code = code;
|
|
389
|
+
err.status = res.status;
|
|
390
|
+
if (data?.needed) err.needed = String(data.needed);
|
|
391
|
+
if (limited) err.rateLimited = true;
|
|
392
|
+
throw err;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
const api = async (method, params, o) => (await call(method, params, o)).data;
|
|
396
|
+
|
|
397
|
+
// --- who is who ------------------------------------------------------------------------
|
|
398
|
+
|
|
399
|
+
let me = null;
|
|
400
|
+
let appId = '';
|
|
401
|
+
const names = new Map(); // user id → {name, at}
|
|
402
|
+
const titles = new Map(); // channel id → {title, at}
|
|
403
|
+
let usersOff = false;
|
|
404
|
+
|
|
405
|
+
function failBotToken() {
|
|
406
|
+
fail(BOT_TOKEN_REJECTED, 'token');
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
async function nameOf(userId) {
|
|
410
|
+
const hit = names.get(userId);
|
|
411
|
+
if (hit && now() - hit.at < NAME_TTL_MS) return hit.name;
|
|
412
|
+
if (usersOff || halted()) return hit?.name ?? '';
|
|
413
|
+
try {
|
|
414
|
+
const u = (await api('users.info', { user: userId }, { timeoutMs: 5000, retries: 1 })).user ?? {};
|
|
415
|
+
const name = cleanName(u.profile?.display_name || u.profile?.real_name || u.real_name || u.name || '');
|
|
416
|
+
remember(names, userId, { name, at: now() }, 1000);
|
|
417
|
+
return name;
|
|
418
|
+
} catch (e) {
|
|
419
|
+
if (e.code === 'missing_scope') {
|
|
420
|
+
usersOff = true;
|
|
421
|
+
log('slack: the bot token lacks users:read, so people show by their Slack ID; add the scope and reinstall the app');
|
|
422
|
+
} else if (BOT_AUTH_ERRORS.has(e.code)) failBotToken();
|
|
423
|
+
else if (e.code === 'user_not_found') remember(names, userId, { name: '', at: now() }, 1000);
|
|
424
|
+
else if (!halted()) log(`slack: ${e.message}`);
|
|
425
|
+
return hit?.name ?? '';
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async function titleOf(channelId) {
|
|
430
|
+
const hit = titles.get(channelId);
|
|
431
|
+
if (hit && now() - hit.at < NAME_TTL_MS) return hit.title;
|
|
432
|
+
if (halted()) return hit?.title ?? '';
|
|
433
|
+
let title = '';
|
|
434
|
+
try {
|
|
435
|
+
const c = (await api('conversations.info', { channel: channelId }, { timeoutMs: 5000, retries: 1 })).channel ?? {};
|
|
436
|
+
const name = cleanName(c.is_mpim ? 'group DM' : c.name ? `#${c.name}` : '');
|
|
437
|
+
title = name && me?.team && !c.is_mpim ? `${me.team} ${name}` : name;
|
|
438
|
+
} catch (e) {
|
|
439
|
+
if (BOT_AUTH_ERRORS.has(e.code)) failBotToken();
|
|
440
|
+
else if (e.code !== 'missing_scope' && e.code !== 'channel_not_found' && !halted()) log(`slack: ${e.message}`);
|
|
441
|
+
}
|
|
442
|
+
remember(titles, channelId, { title, at: now() }, 500);
|
|
443
|
+
return title;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// --- inbound ---------------------------------------------------------------------------
|
|
447
|
+
|
|
448
|
+
const events = new Map(); // event_id → true
|
|
449
|
+
const handled = new Map(); // `${chat}|${ts}` → true: one message as both `message` and `app_mention`
|
|
450
|
+
const roots = new Map(); // `${chat}|${ts}` → its thread
|
|
451
|
+
const lastThread = new Map(); // chat → thread of its latest mention (for the "is thinking…" status)
|
|
452
|
+
let inbound = Promise.resolve();
|
|
453
|
+
|
|
454
|
+
function emit(msg) {
|
|
455
|
+
try {
|
|
456
|
+
const r = onMessage(msg);
|
|
457
|
+
if (r && typeof r.catch === 'function') r.catch((e) => log(`slack: onMessage failed: ${e?.message ?? e}`));
|
|
458
|
+
} catch (e) {
|
|
459
|
+
log(`slack: onMessage threw: ${e?.message ?? e}`);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async function finish(n) {
|
|
464
|
+
const ids = [...new Set([...n.raw.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)].map((m) => m[1]).filter((id) => id !== me.userId))].slice(0, 10);
|
|
465
|
+
const [userName, title, ...others] = await Promise.all([nameOf(n.userId), n.isDirect ? '' : titleOf(n.chatId), ...ids.map((id) => nameOf(id))]);
|
|
466
|
+
const known = new Map(ids.map((id, i) => [id, others[i]]));
|
|
467
|
+
const text = fromSlack(n.raw, { botUserId: me.userId, names: known });
|
|
468
|
+
if (!text) return null;
|
|
469
|
+
return {
|
|
470
|
+
chatId: n.chatId,
|
|
471
|
+
messageId: n.messageId,
|
|
472
|
+
order: n.order,
|
|
473
|
+
userId: n.userId,
|
|
474
|
+
userName: userName || n.profileName || n.userId,
|
|
475
|
+
text,
|
|
476
|
+
isDirect: n.isDirect,
|
|
477
|
+
mentioned: n.mentioned,
|
|
478
|
+
...(title ? { chatTitle: title } : {}),
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function onEvent(payload) {
|
|
483
|
+
if (!me) return;
|
|
484
|
+
const eventId = String(payload?.event_id ?? '');
|
|
485
|
+
if (eventId) {
|
|
486
|
+
if (events.has(eventId)) return;
|
|
487
|
+
remember(events, eventId, true, 1000);
|
|
488
|
+
}
|
|
489
|
+
const n = normalizeEvent(payload?.event, me);
|
|
490
|
+
if (!n) return;
|
|
491
|
+
const k = `${n.chatId}|${n.messageId}`;
|
|
492
|
+
if (handled.has(k)) return;
|
|
493
|
+
remember(handled, k, true, 2000);
|
|
494
|
+
remember(roots, k, n.thread, 2000);
|
|
495
|
+
if (!n.isDirect && n.mentioned) remember(lastThread, n.chatId, n.thread, 500);
|
|
496
|
+
// One at a time, so messages reach the hub in the order Slack sent them.
|
|
497
|
+
inbound = inbound
|
|
498
|
+
.then(() => finish(n))
|
|
499
|
+
.then((msg) => {
|
|
500
|
+
if (msg && !halted()) emit(msg);
|
|
501
|
+
})
|
|
502
|
+
.catch((e) => log(`slack: a message could not be read: ${e?.message ?? e}`));
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// --- Socket Mode -----------------------------------------------------------------------
|
|
506
|
+
|
|
507
|
+
/** The socket events come from (it said hello), and one being opened to replace or restore it. */
|
|
508
|
+
let active = null;
|
|
509
|
+
let opening = null;
|
|
510
|
+
let reconnectTimer = null;
|
|
511
|
+
let checkTimer = null;
|
|
512
|
+
let attempts = 0;
|
|
513
|
+
let healthy = false;
|
|
514
|
+
let earlyCloses = 0; // sockets in a row that closed before hello
|
|
515
|
+
let strikes = 0; // hellos in a row that counted other connections
|
|
516
|
+
let pending = null;
|
|
517
|
+
let startPromise = null;
|
|
518
|
+
|
|
519
|
+
function closeSlot(slot) {
|
|
520
|
+
if (!slot) return;
|
|
521
|
+
slot.closed = true;
|
|
522
|
+
cancel(slot.helloTimer);
|
|
523
|
+
cancel(slot.pingTimer);
|
|
524
|
+
slot.helloTimer = slot.pingTimer = null;
|
|
525
|
+
if (slot.onPing) {
|
|
526
|
+
try {
|
|
527
|
+
pings?.unsubscribe?.(slot.onPing);
|
|
528
|
+
} catch {
|
|
529
|
+
// Gone already.
|
|
530
|
+
}
|
|
531
|
+
slot.onPing = null;
|
|
532
|
+
}
|
|
533
|
+
try {
|
|
534
|
+
slot.ws?.close(1000);
|
|
535
|
+
} catch {
|
|
536
|
+
// Already closed.
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function schedule(delay) {
|
|
541
|
+
cancel(reconnectTimer);
|
|
542
|
+
reconnectTimer = setT(
|
|
543
|
+
guard(() => {
|
|
544
|
+
reconnectTimer = null;
|
|
545
|
+
void openSocket();
|
|
546
|
+
}),
|
|
547
|
+
delay,
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** Something failed: try again with backoff. The first drop after a good connection reads as `connecting`, repeats as `error`. */
|
|
552
|
+
function retry(why) {
|
|
553
|
+
if (halted()) return;
|
|
554
|
+
const delay = backoffDelay(attempts, random);
|
|
555
|
+
attempts += 1;
|
|
556
|
+
const detail = `${why}; reconnecting in ${Math.max(1, Math.round(delay / 1000))} s${earlyCloses >= 3 ? WS_TROUBLE : ''}`;
|
|
557
|
+
log(`slack: ${detail}`);
|
|
558
|
+
if (!active) {
|
|
559
|
+
status(healthy ? 'connecting' : 'error', detail);
|
|
560
|
+
healthy = false;
|
|
561
|
+
}
|
|
562
|
+
schedule(delay);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/** Unrecoverable: no reconnects; `start` rejects if it is still waiting. */
|
|
566
|
+
function fail(detail, hint) {
|
|
567
|
+
if (halted()) return;
|
|
568
|
+
dead = true;
|
|
569
|
+
cancel(reconnectTimer);
|
|
570
|
+
cancel(checkTimer);
|
|
571
|
+
reconnectTimer = checkTimer = null;
|
|
572
|
+
closeSlot(active);
|
|
573
|
+
closeSlot(opening);
|
|
574
|
+
active = opening = null;
|
|
575
|
+
for (const s of sleepers) {
|
|
576
|
+
cancel(s.timer);
|
|
577
|
+
s.reject(stoppedError());
|
|
578
|
+
}
|
|
579
|
+
sleepers.clear();
|
|
580
|
+
log(`slack: ${detail}`);
|
|
581
|
+
status('error', detail, { fatal: true, hint });
|
|
582
|
+
if (pending) {
|
|
583
|
+
pending.reject(Object.assign(new Error(scrub(detail)), { fatal: true, ...(hint ? { hint } : {}) }));
|
|
584
|
+
pending = null;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function watchPings(slot) {
|
|
589
|
+
if (typeof pings?.subscribe !== 'function') return;
|
|
590
|
+
slot.onPing = (m) => {
|
|
591
|
+
try {
|
|
592
|
+
if (!slot.ws || m?.websocket !== slot.ws || slot.closed) return;
|
|
593
|
+
cancel(slot.pingTimer);
|
|
594
|
+
slot.pingTimer = setT(
|
|
595
|
+
guard(() => {
|
|
596
|
+
slot.pingTimer = null;
|
|
597
|
+
if (slot !== active || halted()) return;
|
|
598
|
+
log('slack: no ping from Slack for a minute; reconnecting');
|
|
599
|
+
active = null;
|
|
600
|
+
closeSlot(slot);
|
|
601
|
+
if (!opening) {
|
|
602
|
+
status('connecting', 'The Slack connection went quiet; reconnecting');
|
|
603
|
+
healthy = false;
|
|
604
|
+
void openSocket();
|
|
605
|
+
}
|
|
606
|
+
}),
|
|
607
|
+
PING_TIMEOUT_MS,
|
|
608
|
+
);
|
|
609
|
+
slot.pingTimer?.unref?.();
|
|
610
|
+
} catch {
|
|
611
|
+
// A watchdog must not break the socket.
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
try {
|
|
615
|
+
pings.subscribe(slot.onPing);
|
|
616
|
+
} catch {
|
|
617
|
+
slot.onPing = null;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** Open a socket: the first one, a reconnect, or a replacement while the current one still works. */
|
|
622
|
+
async function openSocket() {
|
|
623
|
+
if (halted() || opening) return;
|
|
624
|
+
cancel(reconnectTimer);
|
|
625
|
+
reconnectTimer = null;
|
|
626
|
+
const slot = { ws: null, closed: false, helloTimer: null, pingTimer: null, onPing: null };
|
|
627
|
+
opening = slot;
|
|
628
|
+
let url;
|
|
629
|
+
try {
|
|
630
|
+
url = (await api('apps.connections.open', {}, { token: appToken })).url;
|
|
631
|
+
} catch (e) {
|
|
632
|
+
if (opening === slot) opening = null;
|
|
633
|
+
if (halted()) return;
|
|
634
|
+
if (BOT_AUTH_ERRORS.has(e.code)) return fail(APP_TOKEN_REJECTED, 'app_token');
|
|
635
|
+
if (e.code === 'missing_scope') return fail(APP_TOKEN_SCOPE, 'app_scope');
|
|
636
|
+
if (e.code === 'not_allowed_token_type') return fail(APP_TOKEN_KIND, 'token_kind');
|
|
637
|
+
if (/socket/i.test(e.code ?? '')) return fail(SOCKET_MODE_OFF, 'socket_mode');
|
|
638
|
+
return retry(e.message);
|
|
639
|
+
}
|
|
640
|
+
if (halted() || opening !== slot) return;
|
|
641
|
+
if (typeof url !== 'string' || !/^wss?:\/\//i.test(url)) {
|
|
642
|
+
opening = null;
|
|
643
|
+
return retry('Slack returned no Socket Mode URL');
|
|
644
|
+
}
|
|
645
|
+
appId = /[?&]app_id=([A-Z0-9]+)/.exec(url)?.[1] ?? appId;
|
|
646
|
+
let ws;
|
|
647
|
+
try {
|
|
648
|
+
ws = new WebSocketImpl(url);
|
|
649
|
+
} catch (e) {
|
|
650
|
+
opening = null;
|
|
651
|
+
return retry(`could not open the Slack connection: ${e?.message ?? e}`);
|
|
652
|
+
}
|
|
653
|
+
slot.ws = ws;
|
|
654
|
+
try {
|
|
655
|
+
ws.binaryType = 'arraybuffer';
|
|
656
|
+
} catch {
|
|
657
|
+
// Not every implementation has it.
|
|
658
|
+
}
|
|
659
|
+
watchPings(slot);
|
|
660
|
+
slot.helloTimer = setT(
|
|
661
|
+
guard(() => {
|
|
662
|
+
slot.helloTimer = null;
|
|
663
|
+
if (opening !== slot) return;
|
|
664
|
+
opening = null;
|
|
665
|
+
closeSlot(slot);
|
|
666
|
+
earlyCloses += 1;
|
|
667
|
+
retry('Slack did not greet the new connection');
|
|
668
|
+
}),
|
|
669
|
+
HELLO_TIMEOUT_MS,
|
|
670
|
+
);
|
|
671
|
+
ws.addEventListener('message', guard((ev) => onFrame(slot, ev?.data)));
|
|
672
|
+
ws.addEventListener('close', guard((ev) => onClose(slot, ev?.code, ev?.reason)));
|
|
673
|
+
ws.addEventListener('error', guard(() => {}));
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function onFrame(slot, data) {
|
|
677
|
+
if (slot.closed || (slot !== active && slot !== opening)) return;
|
|
678
|
+
let p;
|
|
679
|
+
try {
|
|
680
|
+
p = JSON.parse(typeof data === 'string' ? data : Buffer.from(data).toString('utf8'));
|
|
681
|
+
} catch {
|
|
682
|
+
return log('slack: ignored an unreadable Socket Mode frame');
|
|
683
|
+
}
|
|
684
|
+
if (p?.type === 'hello') return onHello(slot, p);
|
|
685
|
+
if (p?.type === 'disconnect') return onDisconnect(slot, String(p.reason ?? ''));
|
|
686
|
+
if (p?.envelope_id) {
|
|
687
|
+
// Acknowledge first: Slack retries an envelope it does not hear back about within 3 s.
|
|
688
|
+
try {
|
|
689
|
+
slot.ws.send(JSON.stringify({ envelope_id: p.envelope_id }));
|
|
690
|
+
} catch (e) {
|
|
691
|
+
log(`slack: could not acknowledge an event: ${e?.message ?? e}`);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
if (p?.type === 'events_api') onEvent(p.payload);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
function onHello(slot, p) {
|
|
698
|
+
if (slot !== opening) return;
|
|
699
|
+
cancel(slot.helloTimer);
|
|
700
|
+
slot.helloTimer = null;
|
|
701
|
+
opening = null;
|
|
702
|
+
const old = active;
|
|
703
|
+
active = slot;
|
|
704
|
+
attempts = 0;
|
|
705
|
+
earlyCloses = 0;
|
|
706
|
+
healthy = true;
|
|
707
|
+
appId = String(p?.connection_info?.app_id || appId || '');
|
|
708
|
+
if (me) remember(APPS, me.userId, { teamId: me.teamId, appId }, 200);
|
|
709
|
+
// Ours: this socket, and the one it replaces until it is closed below.
|
|
710
|
+
const others = Math.max(0, (Number(p?.num_connections) || 1) - (old ? 2 : 1));
|
|
711
|
+
if (old) closeSlot(old);
|
|
712
|
+
cancel(checkTimer);
|
|
713
|
+
checkTimer = null;
|
|
714
|
+
if (others === 0) {
|
|
715
|
+
strikes = 0;
|
|
716
|
+
status('connected');
|
|
717
|
+
} else {
|
|
718
|
+
// A socket of ours that died a moment ago may still be counted: look again with a fresh connection before saying so.
|
|
719
|
+
strikes += 1;
|
|
720
|
+
log(`slack: Slack counts ${others} other Socket Mode connection${others === 1 ? '' : 's'} for this app`);
|
|
721
|
+
if (strikes >= 2) {
|
|
722
|
+
status('error', `Another program is connected to this Slack app (${others} other connection${others === 1 ? '' : 's'}), and Slack hands each message to only one of them. Stop it, or create a separate Slack app for the team.`, { hint: 'conflict' });
|
|
723
|
+
} else status('connected');
|
|
724
|
+
checkTimer = setT(
|
|
725
|
+
guard(() => {
|
|
726
|
+
checkTimer = null;
|
|
727
|
+
if (!halted() && active === slot) void openSocket();
|
|
728
|
+
}),
|
|
729
|
+
strikes >= 2 ? CONFLICT_RECHECK_MS : CONFLICT_CHECK_MS,
|
|
730
|
+
);
|
|
731
|
+
checkTimer?.unref?.();
|
|
732
|
+
}
|
|
733
|
+
if (pending) {
|
|
734
|
+
pending.resolve({ id: me.userId, username: me.user, name: me.name || me.user });
|
|
735
|
+
pending = null;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
function onDisconnect(slot, reason) {
|
|
740
|
+
log(`slack: Slack asked to reconnect (${reason || 'no reason'})`);
|
|
741
|
+
if (reason === 'link_disabled') return fail(SOCKET_MODE_OFF, 'socket_mode');
|
|
742
|
+
if (slot === active) {
|
|
743
|
+
// warning (it closes in about 10 s), refresh_requested, or anything else: replace it now.
|
|
744
|
+
if (!opening) void openSocket();
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
if (slot === opening) {
|
|
748
|
+
opening = null;
|
|
749
|
+
closeSlot(slot);
|
|
750
|
+
retry(`Slack ended the new connection (${reason || 'disconnect'})`);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
function onClose(slot, code, reason) {
|
|
755
|
+
const wasOpening = slot === opening;
|
|
756
|
+
const wasActive = slot === active;
|
|
757
|
+
if (!wasOpening && !wasActive) return;
|
|
758
|
+
closeSlot(slot);
|
|
759
|
+
if (wasOpening) opening = null;
|
|
760
|
+
if (wasActive) active = null;
|
|
761
|
+
if (halted()) return;
|
|
762
|
+
const why = `Slack connection closed (${code ?? 'no code'}${reason ? `: ${reason}` : ''})`;
|
|
763
|
+
if (wasOpening) {
|
|
764
|
+
earlyCloses += 1;
|
|
765
|
+
return retry(why);
|
|
766
|
+
}
|
|
767
|
+
if (opening || reconnectTimer) return; // a replacement is already on its way
|
|
768
|
+
retry(why);
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
async function boot() {
|
|
772
|
+
if (!botToken) return fail(`No Slack bot token. ${BOT_TOKEN_KIND}`, 'token');
|
|
773
|
+
if (!appToken) return fail(`No Slack app-level token. ${APP_TOKEN_KIND}`, 'app_token');
|
|
774
|
+
const problem = tokenProblem(botToken, appToken);
|
|
775
|
+
if (problem) return fail(problem, 'token_kind');
|
|
776
|
+
if (typeof WebSocketImpl !== 'function') return fail('This runtime has no WebSocket');
|
|
777
|
+
if (typeof fetchImpl !== 'function') return fail('This runtime has no fetch');
|
|
778
|
+
status('connecting', 'Connecting to Slack');
|
|
779
|
+
let auth;
|
|
780
|
+
let headers;
|
|
781
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
782
|
+
try {
|
|
783
|
+
({ data: auth, headers } = await call('auth.test', {}, { timeoutMs: 20_000 }));
|
|
784
|
+
break;
|
|
785
|
+
} catch (e) {
|
|
786
|
+
if (halted()) return;
|
|
787
|
+
if (BOT_AUTH_ERRORS.has(e.code)) return fail(BOT_TOKEN_REJECTED, 'token');
|
|
788
|
+
if (e.code === 'not_allowed_token_type') return fail(BOT_TOKEN_KIND, 'token_kind');
|
|
789
|
+
const delay = backoffDelay(attempt, random);
|
|
790
|
+
status('error', `${e.message}; retrying in ${Math.max(1, Math.round(delay / 1000))} s`);
|
|
791
|
+
try {
|
|
792
|
+
await sleep(delay);
|
|
793
|
+
} catch {
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
if (halted()) return;
|
|
799
|
+
if (!auth?.user_id) return fail(`Slack did not say which bot this token belongs to. ${BOT_TOKEN_KIND}`, 'token_kind');
|
|
800
|
+
me = { userId: String(auth.user_id), botId: String(auth.bot_id ?? ''), user: String(auth.user ?? ''), teamId: String(auth.team_id ?? ''), team: cleanName(auth.team), name: '' };
|
|
801
|
+
const granted = headers?.get?.('x-oauth-scopes');
|
|
802
|
+
const missing = missingScopes(granted);
|
|
803
|
+
if (missing.length) {
|
|
804
|
+
return fail(
|
|
805
|
+
`The Slack app is missing the ${missing.join(', ')} scope${missing.length > 1 ? 's' : ''}. Add ${missing.length > 1 ? 'them' : 'it'} under OAuth & Permissions → Bot Token Scopes (or create the app from the manifest), reinstall the app to the workspace, then reconnect.`,
|
|
806
|
+
'scopes',
|
|
807
|
+
);
|
|
808
|
+
}
|
|
809
|
+
const optional = missingScopes(granted, BOT_SCOPES).filter((s) => !REQUIRED_SCOPES.includes(s));
|
|
810
|
+
if (optional.length) log(`slack: the bot token lacks ${optional.join(', ')}; people or channels show by their Slack IDs`);
|
|
811
|
+
me.name = (await nameOf(me.userId)) || me.user;
|
|
812
|
+
if (halted()) return;
|
|
813
|
+
void openSocket();
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// --- Public ----------------------------------------------------------------------------
|
|
817
|
+
|
|
818
|
+
/** Check the bot token, open Socket Mode, resolve with the bot once Slack says hello. Transient failures keep retrying; fatal ones reject. */
|
|
819
|
+
function start() {
|
|
820
|
+
if (stopped) return Promise.reject(new Error('This Slack connector is stopped; create a new one'));
|
|
821
|
+
if (startPromise) return startPromise;
|
|
822
|
+
startPromise = new Promise((resolve, reject) => {
|
|
823
|
+
pending = { resolve, reject };
|
|
824
|
+
});
|
|
825
|
+
startPromise.catch(() => {}); // a fatal error is also reported through onStatus
|
|
826
|
+
void boot().catch((e) => fail(e?.message ?? String(e)));
|
|
827
|
+
return startPromise;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** Close for good: no reconnects, no timers; pending rate-limit waits are cancelled. Idempotent. */
|
|
831
|
+
async function stop() {
|
|
832
|
+
if (stopped) return;
|
|
833
|
+
stopped = true;
|
|
834
|
+
halt.abort();
|
|
835
|
+
cancel(reconnectTimer);
|
|
836
|
+
cancel(checkTimer);
|
|
837
|
+
reconnectTimer = checkTimer = null;
|
|
838
|
+
closeSlot(active);
|
|
839
|
+
closeSlot(opening);
|
|
840
|
+
active = opening = null;
|
|
841
|
+
for (const s of sleepers) {
|
|
842
|
+
cancel(s.timer);
|
|
843
|
+
s.reject(stoppedError());
|
|
844
|
+
}
|
|
845
|
+
sleepers.clear();
|
|
846
|
+
if (pending) {
|
|
847
|
+
pending.reject(new Error('Slack connector stopped before it connected'));
|
|
848
|
+
pending = null;
|
|
849
|
+
}
|
|
850
|
+
status('stopped');
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
async function post(channel, md, thread) {
|
|
854
|
+
const where = { channel, ...(thread ? { thread_ts: thread } : {}) };
|
|
855
|
+
try {
|
|
856
|
+
await api('chat.postMessage', { ...where, text: fallbackText(md), blocks: [{ type: 'markdown', text: defuse(md) }] });
|
|
857
|
+
} catch (e) {
|
|
858
|
+
if (BOT_AUTH_ERRORS.has(e.code)) failBotToken();
|
|
859
|
+
if (!BLOCK_ERRORS.has(e.code)) throw e;
|
|
860
|
+
log(`slack: Slack did not take the Markdown block (${e.code}); sending plain text`);
|
|
861
|
+
await api('chat.postMessage', { ...where, text: fallbackText(md) });
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* Post Markdown `text` to a conversation, in parts of at most 11,000
|
|
867
|
+
* characters (code fences closed and reopened at a cut). With `replyTo` (a
|
|
868
|
+
* message `ts`) every part goes to that message's thread.
|
|
869
|
+
*/
|
|
870
|
+
async function send(chatId, text, sendOpts = {}) {
|
|
871
|
+
if (stopped) throw new Error('Slack connector is stopped');
|
|
872
|
+
const channel = String(chatId);
|
|
873
|
+
const replyTo = sendOpts?.replyTo ? String(sendOpts.replyTo) : '';
|
|
874
|
+
const thread = replyTo ? roots.get(`${channel}|${replyTo}`) ?? replyTo : '';
|
|
875
|
+
for (const part of splitMessage(text, PART_LIMIT)) await post(channel, part, thread);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
const statusAt = new Map();
|
|
879
|
+
let statusOff = false;
|
|
880
|
+
/**
|
|
881
|
+
* Show "<app> is thinking…" under the thread a channel reply will go to;
|
|
882
|
+
* Slack clears it when the reply arrives, or after two minutes. Nothing in a
|
|
883
|
+
* DM: a status there would turn the person's message into a thread.
|
|
884
|
+
*/
|
|
885
|
+
async function typing(chatId) {
|
|
886
|
+
if (halted() || statusOff) return;
|
|
887
|
+
const channel = String(chatId);
|
|
888
|
+
if (channel.startsWith('D')) return;
|
|
889
|
+
const thread = lastThread.get(channel);
|
|
890
|
+
if (!thread) return;
|
|
891
|
+
const k = `${channel}|${thread}`;
|
|
892
|
+
const at = statusAt.get(k);
|
|
893
|
+
if (at !== undefined && now() - at < STATUS_EVERY_MS) return;
|
|
894
|
+
remember(statusAt, k, now(), 200);
|
|
895
|
+
try {
|
|
896
|
+
await api('assistant.threads.setStatus', { channel_id: channel, thread_ts: thread, status: 'is thinking…' }, { timeoutMs: 10_000, retries: 0 });
|
|
897
|
+
} catch (e) {
|
|
898
|
+
if (STATUS_UNSUPPORTED.has(e.code)) {
|
|
899
|
+
statusOff = true;
|
|
900
|
+
log(`slack: no "is thinking…" status in threads (${e.code})`);
|
|
901
|
+
} else if (!halted()) log(`slack: thinking status failed: ${e.message}`);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
return { start, stop, send, typing };
|
|
906
|
+
}
|