@sedge-hq/slack 0.2.0 → 0.3.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 +18 -0
- package/package.json +3 -2
- package/src/api.ts +4 -0
- package/src/slack.ts +151 -38
package/README.md
CHANGED
|
@@ -21,4 +21,22 @@ nobody else gets answers.
|
|
|
21
21
|
Files you send the bot (with `files:read`) are saved for the agent. It can also post in channels
|
|
22
22
|
the bot is in: the agent's `act` tool has a **`post`** action, behind your permissions.
|
|
23
23
|
|
|
24
|
+
## As you, with an account
|
|
25
|
+
|
|
26
|
+
Instead of the bot token, `account` can name a Slack account you signed in to with sedge
|
|
27
|
+
(`sign_in`). **Then sedge reads and posts as you, not as a bot.** Slack lets an app that signs in
|
|
28
|
+
on a computer ask only for user scopes, so the token is yours:
|
|
29
|
+
|
|
30
|
+
- you talk to sedge in your DM with yourself (send `pair <code>` there), and its answers show
|
|
31
|
+
under your name;
|
|
32
|
+
- it reads only that DM, and only what you write there; your other DMs are left alone;
|
|
33
|
+
- its `post` action posts as you, in channels you're in.
|
|
34
|
+
|
|
35
|
+
Socket Mode still needs the app-level token (`appToken`). For the sign-in, under **OAuth &
|
|
36
|
+
Permissions** add the redirect URL `http://localhost:53682/`, turn on PKCE, and add the **user**
|
|
37
|
+
token scopes `chat:write`, `im:history`, `files:read` and `files:write`; under **Event
|
|
38
|
+
Subscriptions**, subscribe to `message.im` on behalf of users. Give sedge the client ID and no
|
|
39
|
+
secret ([Accounts](https://github.com/sedge-hq/sedge/blob/main/docs/accounts.md#slack)). Give
|
|
40
|
+
`botToken` or `account`, not both.
|
|
41
|
+
|
|
24
42
|
[Channels and signals](https://github.com/sedge-hq/sedge/blob/main/docs/channels-and-signals.md) · MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sedge-hq/slack",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Slack for sedge: message your agent from Slack, and it answers there.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sedge",
|
|
@@ -30,7 +30,8 @@
|
|
|
30
30
|
"test": "bun --bun vitest run --passWithNoTests"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@sedge-hq/kit": "0.
|
|
33
|
+
"@sedge-hq/kit": "0.6.0",
|
|
34
|
+
"@sedge-hq/oauth": "0.2.0"
|
|
34
35
|
},
|
|
35
36
|
"devDependencies": {
|
|
36
37
|
"@sedge-hq/config": "0.0.0",
|
package/src/api.ts
CHANGED
|
@@ -10,6 +10,9 @@ export class SlackError extends Error {
|
|
|
10
10
|
|
|
11
11
|
export const DEFAULT_API = 'https://slack.com/api';
|
|
12
12
|
|
|
13
|
+
/** Slack's answers when a token is no good any more. */
|
|
14
|
+
export const REFUSED = new Set(['invalid_auth', 'not_authed', 'token_revoked', 'token_expired']);
|
|
15
|
+
|
|
13
16
|
/** Calls a Web API method with a token; Slack answers `{ ok: false, error }` rather than an HTTP error. */
|
|
14
17
|
export const makeSlack = (api: string, signal: AbortSignal) => {
|
|
15
18
|
const call = async <A = Record<string, unknown>>(
|
|
@@ -65,6 +68,7 @@ export const makeSlack = (api: string, signal: AbortSignal) => {
|
|
|
65
68
|
channel_id: channel,
|
|
66
69
|
...(caption ? { initial_comment: caption } : {}),
|
|
67
70
|
});
|
|
71
|
+
return asked.file_id;
|
|
68
72
|
};
|
|
69
73
|
|
|
70
74
|
return { call, upload };
|
package/src/slack.ts
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import {
|
|
2
|
+
type Account,
|
|
3
|
+
account,
|
|
4
|
+
defineChannel,
|
|
5
|
+
field,
|
|
6
|
+
type ReceivedFile,
|
|
7
|
+
type Reply,
|
|
8
|
+
secret,
|
|
9
|
+
} from '@sedge-hq/kit';
|
|
10
|
+
import { SCOPES, slack as slackProvider } from '@sedge-hq/oauth';
|
|
11
|
+
import { DEFAULT_API, makeSlack, REFUSED, SlackError } from './api';
|
|
3
12
|
import { toMrkdwn } from './mrkdwn';
|
|
4
13
|
|
|
5
14
|
/** Slack's limit for one block of text. */
|
|
@@ -42,6 +51,7 @@ interface Envelope {
|
|
|
42
51
|
readonly bot_id?: string;
|
|
43
52
|
readonly subtype?: string;
|
|
44
53
|
readonly files?: ReadonlyArray<{
|
|
54
|
+
readonly id?: string;
|
|
45
55
|
readonly name?: string;
|
|
46
56
|
readonly mimetype?: string;
|
|
47
57
|
readonly url_private_download?: string;
|
|
@@ -58,6 +68,34 @@ interface Envelope {
|
|
|
58
68
|
};
|
|
59
69
|
}
|
|
60
70
|
|
|
71
|
+
/** The token for Web API calls: the bot's, or, with an account, yours (refreshed when it's due). */
|
|
72
|
+
const tokenFor = (settings: { botToken?: string | undefined; account?: Account | undefined }) => {
|
|
73
|
+
const { botToken, account } = settings;
|
|
74
|
+
return async () => {
|
|
75
|
+
if (account) return account.token();
|
|
76
|
+
if (!botToken) throw new Error('Give the bot token, or a Slack account to act as.');
|
|
77
|
+
return botToken;
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/** Calls Slack; a refused token on an account tells sedge, so it can ask you to sign in again. */
|
|
82
|
+
const calling = (
|
|
83
|
+
slack: ReturnType<typeof makeSlack>,
|
|
84
|
+
token: () => Promise<string>,
|
|
85
|
+
account: Account | undefined,
|
|
86
|
+
) => {
|
|
87
|
+
const refused = (error: unknown) => {
|
|
88
|
+
if (error instanceof SlackError && REFUSED.has(error.code)) account?.refused();
|
|
89
|
+
throw error;
|
|
90
|
+
};
|
|
91
|
+
return {
|
|
92
|
+
call: async <A = Record<string, unknown>>(method: string, body?: Record<string, unknown>) =>
|
|
93
|
+
slack.call<A>(method, await token(), body).catch(refused),
|
|
94
|
+
upload: async (channel: string, path: string, caption?: string) =>
|
|
95
|
+
slack.upload(await token(), channel, path, caption).catch(refused),
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
|
|
61
99
|
/**
|
|
62
100
|
* Slack as a sedge channel: message the bot in a DM, and sedge answers there. It connects with
|
|
63
101
|
* Socket Mode, so nothing has to be reachable from the internet.
|
|
@@ -67,49 +105,82 @@ interface Envelope {
|
|
|
67
105
|
* the bot scopes `chat:write`, `im:history`, `files:write` and `files:read` (for files you send it). Install it, and give sedge both
|
|
68
106
|
* tokens.
|
|
69
107
|
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
108
|
+
* Or, instead of the bot token, a Slack account signed in to with sedge: then it reads and posts
|
|
109
|
+
* as you, not as a bot, in your DM with yourself, because Slack gives apps that sign in on a
|
|
110
|
+
* computer user tokens only. Socket Mode still needs the app-level token.
|
|
111
|
+
*
|
|
112
|
+
* It only talks to people paired through an invite: they send `pair <code>`, with a code shown
|
|
113
|
+
* only on your screen. Everyone else gets no answer.
|
|
72
114
|
*/
|
|
73
115
|
export default defineChannel({
|
|
74
116
|
name: 'slack',
|
|
75
117
|
summary: 'your Slack: message sedge in a DM, and it answers there',
|
|
76
118
|
settings: {
|
|
77
119
|
appToken: secret(
|
|
78
|
-
'The app-level token (xapp-…), from Basic Information → App-Level Tokens, with connections:write.',
|
|
120
|
+
'The app-level token (xapp-…), from Basic Information → App-Level Tokens, with connections:write. Needed for Socket Mode, with a bot token or an account.',
|
|
121
|
+
),
|
|
122
|
+
botToken: field.optional(
|
|
123
|
+
secret(
|
|
124
|
+
'The bot token (xoxb-…), from OAuth & Permissions: sedge answers as the bot. Leave it out when you give an account instead.',
|
|
125
|
+
),
|
|
126
|
+
),
|
|
127
|
+
account: field.optional(
|
|
128
|
+
account(
|
|
129
|
+
'A Slack account signed in to with sedge (sign_in), instead of the bot token. sedge then reads and posts AS YOU, not as a bot: you talk to it in your DM with yourself, and its answers show under your name.',
|
|
130
|
+
[
|
|
131
|
+
slackProvider([
|
|
132
|
+
SCOPES.slackChatWrite,
|
|
133
|
+
SCOPES.slackImHistory,
|
|
134
|
+
SCOPES.slackFilesRead,
|
|
135
|
+
SCOPES.slackFilesWrite,
|
|
136
|
+
]),
|
|
137
|
+
],
|
|
138
|
+
{ instead: 'botToken' },
|
|
139
|
+
),
|
|
79
140
|
),
|
|
80
|
-
botToken: secret('The bot token (xoxb-…), from OAuth & Permissions.'),
|
|
81
141
|
api: field.optional(field.text('The Slack API address. Default: slack.com/api.')),
|
|
82
142
|
},
|
|
83
143
|
actions: {
|
|
84
144
|
post: {
|
|
85
145
|
description:
|
|
86
|
-
'Post a message in a Slack channel
|
|
146
|
+
'Post a message in a Slack channel (not a DM with the user: send_message does that). With a bot token it posts as the bot, in channels it is in; with an account it posts as the user. Needs chat:write.',
|
|
87
147
|
input: {
|
|
88
148
|
channel: field.text('The channel: its ID (C0123…) or #name.'),
|
|
89
149
|
text: field.text('The message, in Markdown.'),
|
|
90
150
|
},
|
|
91
|
-
run: async ({ channel, text },
|
|
92
|
-
const slack =
|
|
93
|
-
|
|
151
|
+
run: async ({ channel, text }, settings, kit) => {
|
|
152
|
+
const slack = calling(
|
|
153
|
+
makeSlack(settings.api ?? DEFAULT_API, kit.signal),
|
|
154
|
+
tokenFor(settings),
|
|
155
|
+
settings.account,
|
|
156
|
+
);
|
|
157
|
+
await slack.call('chat.postMessage', {
|
|
94
158
|
channel,
|
|
95
159
|
unfurl_links: false,
|
|
96
160
|
...blocks({ text }),
|
|
97
161
|
});
|
|
98
|
-
return `Posted in ${channel}.`;
|
|
162
|
+
return `Posted in ${channel}${settings.account ? ' as you' : ''}.`;
|
|
99
163
|
},
|
|
100
164
|
},
|
|
101
165
|
},
|
|
102
|
-
connect: async (
|
|
103
|
-
const
|
|
166
|
+
connect: async (settings, kit) => {
|
|
167
|
+
const { appToken, api } = settings;
|
|
168
|
+
// With an account, sedge is you: it answers in your DM with yourself, under your name.
|
|
169
|
+
const asYou = settings.account !== undefined;
|
|
170
|
+
const raw = makeSlack(api ?? DEFAULT_API, kit.signal);
|
|
171
|
+
const slack = calling(raw, tokenFor(settings), settings.account);
|
|
104
172
|
const me = await slack.call<{
|
|
105
173
|
user_id: string;
|
|
106
174
|
team_id: string;
|
|
107
|
-
bot_id
|
|
175
|
+
bot_id?: string;
|
|
108
176
|
team?: string;
|
|
109
|
-
}>('auth.test'
|
|
110
|
-
const bot =
|
|
111
|
-
|
|
112
|
-
|
|
177
|
+
}>('auth.test');
|
|
178
|
+
const bot =
|
|
179
|
+
asYou || !me.bot_id
|
|
180
|
+
? { bot: undefined }
|
|
181
|
+
: await slack
|
|
182
|
+
.call<{ bot?: { app_id?: string } }>('bots.info', { bot: me.bot_id })
|
|
183
|
+
.catch(() => ({ bot: undefined }));
|
|
113
184
|
const appId = bot.bot?.app_id;
|
|
114
185
|
|
|
115
186
|
const paired = new Set<string>(
|
|
@@ -119,17 +190,49 @@ export default defineChannel({
|
|
|
119
190
|
const showStatus = () =>
|
|
120
191
|
kit.status(
|
|
121
192
|
paired.size > 0
|
|
122
|
-
? `${me.team ?? me.team_id} · paired`
|
|
123
|
-
: `${me.team ?? me.team_id} · send the bot the pairing code`,
|
|
193
|
+
? `${me.team ?? me.team_id} · paired${asYou ? ', as you' : ''}`
|
|
194
|
+
: `${me.team ?? me.team_id} · send ${asYou ? 'yourself' : 'the bot'} the pairing code`,
|
|
124
195
|
);
|
|
125
196
|
showStatus();
|
|
126
197
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
198
|
+
// As you, what sedge posts comes back as your own messages: those are not for it.
|
|
199
|
+
const sent = new Set<string>();
|
|
200
|
+
const sentFiles = new Set<string>();
|
|
201
|
+
const sentTexts: Array<string> = [];
|
|
202
|
+
const remember = <A>(set: Set<A>, value: A) => {
|
|
203
|
+
set.add(value);
|
|
204
|
+
if (set.size > 200) set.delete(set.values().next().value as A);
|
|
205
|
+
};
|
|
206
|
+
const ours = (event: NonNullable<NonNullable<Envelope['payload']>['event']>) => {
|
|
207
|
+
if (!asYou) return false;
|
|
208
|
+
if (event.ts && sent.has(event.ts)) return true;
|
|
209
|
+
const files = event.files ?? [];
|
|
210
|
+
if (files.length > 0 && files.every((f) => f.id && sentFiles.has(f.id))) return true;
|
|
211
|
+
// The event can beat chat.postMessage's answer: match the text while it's in flight.
|
|
212
|
+
const i = sentTexts.indexOf(event.text ?? '');
|
|
213
|
+
if (i >= 0) {
|
|
214
|
+
sentTexts.splice(i, 1);
|
|
215
|
+
return true;
|
|
216
|
+
}
|
|
217
|
+
return false;
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
/** A text sedge is about to post as you, so its echo isn't taken for yours. */
|
|
221
|
+
const sending = (text: string) => {
|
|
222
|
+
if (!asYou) return;
|
|
223
|
+
sentTexts.push(text);
|
|
224
|
+
setTimeout(() => {
|
|
225
|
+
const i = sentTexts.indexOf(text);
|
|
226
|
+
if (i >= 0) sentTexts.splice(i, 1);
|
|
227
|
+
}, 30_000).unref?.();
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
const post = async (channel: string, reply: Reply) => {
|
|
231
|
+
const message = { channel, unfurl_links: false, ...blocks(reply) };
|
|
232
|
+
sending(message.text);
|
|
233
|
+
const answer = await slack.call<{ ts?: string }>('chat.postMessage', message);
|
|
234
|
+
if (asYou && answer.ts) remember(sent, answer.ts);
|
|
235
|
+
};
|
|
133
236
|
|
|
134
237
|
const handle = async (envelope: Envelope) => {
|
|
135
238
|
const event = envelope.payload?.event;
|
|
@@ -144,6 +247,10 @@ export default defineChannel({
|
|
|
144
247
|
!event.channel
|
|
145
248
|
)
|
|
146
249
|
return;
|
|
250
|
+
if (ours(event)) return;
|
|
251
|
+
// As you, Slack sends every DM you're in: only yours, and only in the paired one.
|
|
252
|
+
if (asYou && (event.user !== me.user_id || (home && event.channel !== home)))
|
|
253
|
+
return;
|
|
147
254
|
const pair = /^\s*pair\s+(\S+)\s*$/i.exec(event.text ?? '');
|
|
148
255
|
if (pair && !paired.has(event.user)) {
|
|
149
256
|
if (await kit.claim(pair[1]!, event.user)) {
|
|
@@ -152,7 +259,9 @@ export default defineChannel({
|
|
|
152
259
|
await kit.memo.set('paired', JSON.stringify([...paired]));
|
|
153
260
|
await kit.memo.set('home', home);
|
|
154
261
|
await post(event.channel, {
|
|
155
|
-
text:
|
|
262
|
+
text: asYou
|
|
263
|
+
? "Paired. I'm sedge, and I write here as you; write to me here any time."
|
|
264
|
+
: "Paired. I'm sedge; write to me here any time.",
|
|
156
265
|
});
|
|
157
266
|
showStatus();
|
|
158
267
|
}
|
|
@@ -161,7 +270,7 @@ export default defineChannel({
|
|
|
161
270
|
if (!paired.has(event.user)) return;
|
|
162
271
|
home = event.channel;
|
|
163
272
|
await kit.memo.set('home', home);
|
|
164
|
-
// Files they shared: fetched with the
|
|
273
|
+
// Files they shared: fetched with the token (it needs files:read) and saved.
|
|
165
274
|
const files: Array<ReceivedFile> = [];
|
|
166
275
|
const missed: Array<string> = [];
|
|
167
276
|
for (const file of event.files ?? []) {
|
|
@@ -169,7 +278,7 @@ export default defineChannel({
|
|
|
169
278
|
try {
|
|
170
279
|
if (!file.url_private_download) throw new Error('no download link');
|
|
171
280
|
const response = await fetch(file.url_private_download, {
|
|
172
|
-
headers: { authorization: `Bearer ${
|
|
281
|
+
headers: { authorization: `Bearer ${await tokenFor(settings)()}` },
|
|
173
282
|
signal: AbortSignal.any([kit.signal, AbortSignal.timeout(120_000)]),
|
|
174
283
|
});
|
|
175
284
|
// Without files:read, Slack answers with its login page instead.
|
|
@@ -212,7 +321,7 @@ export default defineChannel({
|
|
|
212
321
|
// The buttons go; what was picked stays in the message.
|
|
213
322
|
if (payload.message?.ts) {
|
|
214
323
|
await slack
|
|
215
|
-
.call('chat.update',
|
|
324
|
+
.call('chat.update', {
|
|
216
325
|
channel,
|
|
217
326
|
ts: payload.message.ts,
|
|
218
327
|
text: `${payload.message.text ?? ''}\n\n✓ ${action.text?.text ?? action.value}`,
|
|
@@ -232,7 +341,9 @@ export default defineChannel({
|
|
|
232
341
|
const chatFor = (to?: string) => {
|
|
233
342
|
const channel = to ?? home;
|
|
234
343
|
if (!channel || paired.size === 0)
|
|
235
|
-
throw new Error(
|
|
344
|
+
throw new Error(
|
|
345
|
+
`Slack is not paired yet: send ${asYou ? 'yourself' : 'the bot'} the pairing code first.`,
|
|
346
|
+
);
|
|
236
347
|
return channel;
|
|
237
348
|
};
|
|
238
349
|
|
|
@@ -240,10 +351,7 @@ export default defineChannel({
|
|
|
240
351
|
// Socket Mode: a WebSocket Slack hands events to. Each is acknowledged at once; when Slack
|
|
241
352
|
// says it's moving the connection, this returns an error and the kit connects again.
|
|
242
353
|
listen: async () => {
|
|
243
|
-
const { url } = await
|
|
244
|
-
'apps.connections.open',
|
|
245
|
-
appToken,
|
|
246
|
-
);
|
|
354
|
+
const { url } = await raw.call<{ url: string }>('apps.connections.open', appToken);
|
|
247
355
|
await new Promise<void>((resolve, reject) => {
|
|
248
356
|
const socket = new WebSocket(url);
|
|
249
357
|
const stop = () => {
|
|
@@ -272,12 +380,17 @@ export default defineChannel({
|
|
|
272
380
|
});
|
|
273
381
|
},
|
|
274
382
|
invite: (code) =>
|
|
275
|
-
|
|
383
|
+
asYou
|
|
384
|
+
? `In Slack, open your DM with yourself (your own name under Direct messages) and send this message: pair ${code}. sedge reads and answers there as you.`
|
|
385
|
+
: `In Slack, send the sedge bot this message: pair ${code}${appId ? ` (open its DM: https://slack.com/app_redirect?app=${appId}&team=${me.team_id})` : ''}`,
|
|
276
386
|
deliver: async (reply, to) => {
|
|
277
387
|
const channel = chatFor(to);
|
|
278
388
|
await post(channel, reply);
|
|
279
|
-
for (const file of reply.files ?? [])
|
|
280
|
-
|
|
389
|
+
for (const file of reply.files ?? []) {
|
|
390
|
+
if (file.caption) sending(file.caption);
|
|
391
|
+
const id = await slack.upload(channel, file.path, file.caption);
|
|
392
|
+
if (asYou) remember(sentFiles, id);
|
|
393
|
+
}
|
|
281
394
|
},
|
|
282
395
|
};
|
|
283
396
|
},
|