@sedge-hq/slack 0.0.0-stage → 0.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.
- package/README.md +20 -2
- package/package.json +45 -5
- package/src/api.ts +71 -0
- package/src/mrkdwn.ts +25 -0
- package/src/slack.ts +225 -0
package/README.md
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sedge-hq/slack
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Slack for [sedge](https://sedge.sh): message your agent in a DM, and it answers there, with buttons
|
|
4
|
+
for its questions and approvals.
|
|
5
|
+
|
|
6
|
+
It uses Socket Mode, so nothing has to be reachable from the internet. Make an app at
|
|
7
|
+
[api.slack.com/apps](https://api.slack.com/apps):
|
|
8
|
+
|
|
9
|
+
1. **Socket Mode**: turn it on; create the app-level token it offers (`xapp-…`, with
|
|
10
|
+
`connections:write`).
|
|
11
|
+
2. **Event Subscriptions**: subscribe to the bot event `message.im`.
|
|
12
|
+
3. **Interactivity & Shortcuts**: turn it on (needed for buttons).
|
|
13
|
+
4. **App Home**: allow users to send messages from the Messages tab.
|
|
14
|
+
5. **OAuth & Permissions**: add the bot scopes `chat:write`, `im:history` and `files:write`;
|
|
15
|
+
install the app, and copy the bot token (`xoxb-…`).
|
|
16
|
+
|
|
17
|
+
Then in `sedge`, say "set up slack": it asks for both tokens in hidden fields, keeps them in your
|
|
18
|
+
keychain, and shows you a code. Send the bot `pair <code>` in a DM: that pairs your account, and
|
|
19
|
+
nobody else gets answers.
|
|
20
|
+
|
|
21
|
+
[Channels and signals](https://github.com/sedge-hq/sedge/blob/main/docs/channels-and-signals.md) · MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@sedge-hq/slack",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Slack for sedge: message your agent from Slack, and it answers there.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"sedge",
|
|
7
|
+
"sedge-kit",
|
|
8
|
+
"slack"
|
|
9
|
+
],
|
|
10
|
+
"homepage": "https://sedge.sh",
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/sedge-hq/sedge.git",
|
|
15
|
+
"directory": "packages/slack"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"src",
|
|
19
|
+
"!src/**/*.test.ts"
|
|
20
|
+
],
|
|
21
|
+
"type": "module",
|
|
22
|
+
"exports": {
|
|
23
|
+
".": "./src/slack.ts"
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"typecheck": "tsc --noEmit",
|
|
30
|
+
"test": "bun --bun vitest run --passWithNoTests"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@sedge-hq/kit": "0.3.2"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@sedge-hq/config": "0.0.0",
|
|
37
|
+
"@types/bun": "1.4.4",
|
|
38
|
+
"typescript": "7.0.2",
|
|
39
|
+
"vitest": "5.1.1"
|
|
40
|
+
},
|
|
41
|
+
"sedge": {
|
|
42
|
+
"plugins": [
|
|
43
|
+
"./src/slack.ts"
|
|
44
|
+
]
|
|
45
|
+
}
|
|
46
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** A Slack Web API error: Slack's own code, such as `not_in_channel` or `invalid_auth`. */
|
|
2
|
+
export class SlackError extends Error {
|
|
3
|
+
constructor(
|
|
4
|
+
readonly method: string,
|
|
5
|
+
readonly code: string,
|
|
6
|
+
) {
|
|
7
|
+
super(`${method}: ${code}`);
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_API = 'https://slack.com/api';
|
|
12
|
+
|
|
13
|
+
/** Calls a Web API method with a token; Slack answers `{ ok: false, error }` rather than an HTTP error. */
|
|
14
|
+
export const makeSlack = (api: string, signal: AbortSignal) => {
|
|
15
|
+
const call = async <A = Record<string, unknown>>(
|
|
16
|
+
method: string,
|
|
17
|
+
token: string,
|
|
18
|
+
body: Record<string, unknown> = {},
|
|
19
|
+
): Promise<A> => {
|
|
20
|
+
const response = await fetch(`${api.replace(/\/$/, '')}/${method}`, {
|
|
21
|
+
method: 'POST',
|
|
22
|
+
headers: {
|
|
23
|
+
authorization: `Bearer ${token}`,
|
|
24
|
+
'content-type': 'application/json; charset=utf-8',
|
|
25
|
+
},
|
|
26
|
+
body: JSON.stringify(body),
|
|
27
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
|
|
28
|
+
});
|
|
29
|
+
const payload = (await response.json().catch(() => ({}))) as {
|
|
30
|
+
ok?: boolean;
|
|
31
|
+
error?: string;
|
|
32
|
+
};
|
|
33
|
+
if (!payload.ok) throw new SlackError(method, payload.error ?? `HTTP ${response.status}`);
|
|
34
|
+
return payload as A;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** Slack's three-step upload: ask for a URL, send the bytes, share the file in the chat. */
|
|
38
|
+
const upload = async (token: string, channel: string, path: string, caption?: string) => {
|
|
39
|
+
const file = Bun.file(path);
|
|
40
|
+
const name = path.split('/').pop() ?? 'file';
|
|
41
|
+
const form = new URLSearchParams({ filename: name, length: String(file.size) });
|
|
42
|
+
const asked = await fetch(`${api.replace(/\/$/, '')}/files.getUploadURLExternal`, {
|
|
43
|
+
method: 'POST',
|
|
44
|
+
headers: {
|
|
45
|
+
authorization: `Bearer ${token}`,
|
|
46
|
+
'content-type': 'application/x-www-form-urlencoded',
|
|
47
|
+
},
|
|
48
|
+
body: form,
|
|
49
|
+
signal,
|
|
50
|
+
}).then(
|
|
51
|
+
(r) =>
|
|
52
|
+
r.json() as Promise<{
|
|
53
|
+
ok?: boolean;
|
|
54
|
+
error?: string;
|
|
55
|
+
upload_url?: string;
|
|
56
|
+
file_id?: string;
|
|
57
|
+
}>,
|
|
58
|
+
);
|
|
59
|
+
if (!asked.ok || !asked.upload_url || !asked.file_id) {
|
|
60
|
+
throw new SlackError('files.getUploadURLExternal', asked.error ?? 'no upload url');
|
|
61
|
+
}
|
|
62
|
+
await fetch(asked.upload_url, { method: 'POST', body: file, signal });
|
|
63
|
+
await call('files.completeUploadExternal', token, {
|
|
64
|
+
files: [{ id: asked.file_id, title: name }],
|
|
65
|
+
channel_id: channel,
|
|
66
|
+
...(caption ? { initial_comment: caption } : {}),
|
|
67
|
+
});
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
return { call, upload };
|
|
71
|
+
};
|
package/src/mrkdwn.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Markdown, as the agent writes it, in Slack's own "mrkdwn": *bold*, _italic_, ~strike~,
|
|
3
|
+
* <url|links>, and code as it is. Code is set aside first so nothing inside it changes.
|
|
4
|
+
*/
|
|
5
|
+
export const toMrkdwn = (markdown: string) => {
|
|
6
|
+
const code: Array<string> = [];
|
|
7
|
+
const keep = (text: string) => `\uE000${code.push(text) - 1}\uE000`;
|
|
8
|
+
let text = markdown
|
|
9
|
+
.replace(/```[\s\S]*?```/g, (block) => keep(block.replace(/^```\w*\n?/, '```\n')))
|
|
10
|
+
.replace(/`[^`\n]+`/g, keep);
|
|
11
|
+
// Slack wants &, < and > escaped outside its own markup.
|
|
12
|
+
text = text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
13
|
+
text = text
|
|
14
|
+
.replace(/^#{1,6}\s+(.+)$/gm, '\uE001$1\uE001')
|
|
15
|
+
.replace(
|
|
16
|
+
/\*\*(.+?)\*\*|__(.+?)__/g,
|
|
17
|
+
(_, a: string | undefined, b: string | undefined) => `\uE001${a ?? b}\uE001`,
|
|
18
|
+
)
|
|
19
|
+
.replace(/(?<![*\w])\*(?!\s)([^*\n]+?)\*(?!\w)/g, '_$1_')
|
|
20
|
+
.replace(/\uE001/g, '*')
|
|
21
|
+
.replace(/~~(.+?)~~/g, '~$1~')
|
|
22
|
+
.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '<$2|$1>')
|
|
23
|
+
.replace(/^(\s*)[-*]\s+/gm, '$1• ');
|
|
24
|
+
return text.replace(/\uE000(\d+)\uE000/g, (_, i: string) => code[Number(i)]!);
|
|
25
|
+
};
|
package/src/slack.ts
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { defineChannel, field, type Reply, secret } from '@sedge-hq/kit';
|
|
2
|
+
import { DEFAULT_API, makeSlack } from './api';
|
|
3
|
+
import { toMrkdwn } from './mrkdwn';
|
|
4
|
+
|
|
5
|
+
/** Slack's limit for one block of text. */
|
|
6
|
+
const SECTION = 3000;
|
|
7
|
+
|
|
8
|
+
const blocks = (reply: Reply) => {
|
|
9
|
+
const text = toMrkdwn(reply.text);
|
|
10
|
+
const sections = [];
|
|
11
|
+
for (let i = 0; i < text.length; i += SECTION) {
|
|
12
|
+
sections.push({
|
|
13
|
+
type: 'section',
|
|
14
|
+
text: { type: 'mrkdwn', text: text.slice(i, i + SECTION) },
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
if (reply.choices?.length) {
|
|
18
|
+
sections.push({
|
|
19
|
+
type: 'actions',
|
|
20
|
+
elements: reply.choices.slice(0, 25).map((choice, i) => ({
|
|
21
|
+
type: 'button',
|
|
22
|
+
action_id: `sedge-${i}`,
|
|
23
|
+
text: { type: 'plain_text', text: choice.label.slice(0, 75) },
|
|
24
|
+
value: choice.value.slice(0, 2000),
|
|
25
|
+
})),
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
return { text, blocks: sections };
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
interface Envelope {
|
|
32
|
+
readonly envelope_id?: string;
|
|
33
|
+
readonly type: string;
|
|
34
|
+
readonly payload?: {
|
|
35
|
+
readonly event?: {
|
|
36
|
+
readonly type?: string;
|
|
37
|
+
readonly channel_type?: string;
|
|
38
|
+
readonly channel?: string;
|
|
39
|
+
readonly user?: string;
|
|
40
|
+
readonly text?: string;
|
|
41
|
+
readonly ts?: string;
|
|
42
|
+
readonly bot_id?: string;
|
|
43
|
+
readonly subtype?: string;
|
|
44
|
+
};
|
|
45
|
+
readonly type?: string;
|
|
46
|
+
readonly user?: { readonly id?: string };
|
|
47
|
+
readonly channel?: { readonly id?: string };
|
|
48
|
+
readonly actions?: ReadonlyArray<{
|
|
49
|
+
readonly value?: string;
|
|
50
|
+
readonly text?: { readonly text?: string };
|
|
51
|
+
}>;
|
|
52
|
+
readonly message?: { readonly ts?: string; readonly text?: string };
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Slack as a sedge channel: message the bot in a DM, and sedge answers there. It connects with
|
|
58
|
+
* Socket Mode, so nothing has to be reachable from the internet.
|
|
59
|
+
*
|
|
60
|
+
* Make an app at api.slack.com/apps: turn on Socket Mode (that gives the app-level token, with
|
|
61
|
+
* `connections:write`), subscribe to the `message.im` bot event, turn on Interactivity, and add
|
|
62
|
+
* the bot scopes `chat:write`, `im:history` and `files:write`. Install it, and give sedge both
|
|
63
|
+
* tokens.
|
|
64
|
+
*
|
|
65
|
+
* It only talks to people paired through an invite: they send the bot `pair <code>`, with a code
|
|
66
|
+
* shown only on your screen. Everyone else gets no answer.
|
|
67
|
+
*/
|
|
68
|
+
export default defineChannel({
|
|
69
|
+
name: 'slack',
|
|
70
|
+
summary: 'your Slack: message sedge in a DM, and it answers there',
|
|
71
|
+
settings: {
|
|
72
|
+
appToken: secret(
|
|
73
|
+
'The app-level token (xapp-…), from Basic Information → App-Level Tokens, with connections:write.',
|
|
74
|
+
),
|
|
75
|
+
botToken: secret('The bot token (xoxb-…), from OAuth & Permissions.'),
|
|
76
|
+
api: field.optional(field.text('The Slack API address. Default: slack.com/api.')),
|
|
77
|
+
},
|
|
78
|
+
connect: async ({ appToken, botToken, api }, kit) => {
|
|
79
|
+
const slack = makeSlack(api ?? DEFAULT_API, kit.signal);
|
|
80
|
+
const me = await slack.call<{
|
|
81
|
+
user_id: string;
|
|
82
|
+
team_id: string;
|
|
83
|
+
bot_id: string;
|
|
84
|
+
team?: string;
|
|
85
|
+
}>('auth.test', botToken);
|
|
86
|
+
const bot = await slack
|
|
87
|
+
.call<{ bot?: { app_id?: string } }>('bots.info', botToken, { bot: me.bot_id })
|
|
88
|
+
.catch(() => ({ bot: undefined }));
|
|
89
|
+
const appId = bot.bot?.app_id;
|
|
90
|
+
|
|
91
|
+
const paired = new Set<string>(
|
|
92
|
+
JSON.parse((await kit.memo.get('paired')) ?? '[]') as Array<string>,
|
|
93
|
+
);
|
|
94
|
+
let home = (await kit.memo.get('home')) ?? undefined;
|
|
95
|
+
const showStatus = () =>
|
|
96
|
+
kit.status(
|
|
97
|
+
paired.size > 0
|
|
98
|
+
? `${me.team ?? me.team_id} · paired`
|
|
99
|
+
: `${me.team ?? me.team_id} · send the bot the pairing code`,
|
|
100
|
+
);
|
|
101
|
+
showStatus();
|
|
102
|
+
|
|
103
|
+
const post = (channel: string, reply: Reply) =>
|
|
104
|
+
slack.call('chat.postMessage', botToken, {
|
|
105
|
+
channel,
|
|
106
|
+
unfurl_links: false,
|
|
107
|
+
...blocks(reply),
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
const handle = async (envelope: Envelope) => {
|
|
111
|
+
const event = envelope.payload?.event;
|
|
112
|
+
if (envelope.type === 'events_api' && event?.type === 'message') {
|
|
113
|
+
// Direct messages from people only: not the bot's own, not edits, not channels.
|
|
114
|
+
if (
|
|
115
|
+
event.channel_type !== 'im' ||
|
|
116
|
+
event.bot_id ||
|
|
117
|
+
event.subtype ||
|
|
118
|
+
!event.user ||
|
|
119
|
+
!event.channel
|
|
120
|
+
)
|
|
121
|
+
return;
|
|
122
|
+
const pair = /^\s*pair\s+(\S+)\s*$/i.exec(event.text ?? '');
|
|
123
|
+
if (pair && !paired.has(event.user)) {
|
|
124
|
+
if (await kit.claim(pair[1]!, event.user)) {
|
|
125
|
+
paired.add(event.user);
|
|
126
|
+
home = event.channel;
|
|
127
|
+
await kit.memo.set('paired', JSON.stringify([...paired]));
|
|
128
|
+
await kit.memo.set('home', home);
|
|
129
|
+
await post(event.channel, {
|
|
130
|
+
text: "Paired. I'm sedge; write to me here any time.",
|
|
131
|
+
});
|
|
132
|
+
showStatus();
|
|
133
|
+
}
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (!paired.has(event.user)) return;
|
|
137
|
+
home = event.channel;
|
|
138
|
+
await kit.memo.set('home', home);
|
|
139
|
+
if (!event.text) return;
|
|
140
|
+
return kit.receive({
|
|
141
|
+
type: 'message',
|
|
142
|
+
from: event.channel,
|
|
143
|
+
text: event.text,
|
|
144
|
+
key: event.ts ?? '',
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
const payload = envelope.payload;
|
|
148
|
+
if (envelope.type === 'interactive' && payload?.type === 'block_actions') {
|
|
149
|
+
const user = payload.user?.id;
|
|
150
|
+
const channel = payload.channel?.id;
|
|
151
|
+
const action = payload.actions?.[0];
|
|
152
|
+
if (!user || !channel || !action?.value || !paired.has(user)) return;
|
|
153
|
+
// The buttons go; what was picked stays in the message.
|
|
154
|
+
if (payload.message?.ts) {
|
|
155
|
+
await slack
|
|
156
|
+
.call('chat.update', botToken, {
|
|
157
|
+
channel,
|
|
158
|
+
ts: payload.message.ts,
|
|
159
|
+
text: `${payload.message.text ?? ''}\n\n✓ ${action.text?.text ?? action.value}`,
|
|
160
|
+
blocks: [],
|
|
161
|
+
})
|
|
162
|
+
.catch(() => undefined);
|
|
163
|
+
}
|
|
164
|
+
return kit.receive({
|
|
165
|
+
type: 'picked',
|
|
166
|
+
from: channel,
|
|
167
|
+
value: action.value,
|
|
168
|
+
key: `${payload.message?.ts}:${action.value}`,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const chatFor = (to?: string) => {
|
|
174
|
+
const channel = to ?? home;
|
|
175
|
+
if (!channel || paired.size === 0)
|
|
176
|
+
throw new Error('Slack is not paired yet: send the bot the pairing code first.');
|
|
177
|
+
return channel;
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
return {
|
|
181
|
+
// Socket Mode: a WebSocket Slack hands events to. Each is acknowledged at once; when Slack
|
|
182
|
+
// says it's moving the connection, this returns an error and the kit connects again.
|
|
183
|
+
listen: async () => {
|
|
184
|
+
const { url } = await slack.call<{ url: string }>(
|
|
185
|
+
'apps.connections.open',
|
|
186
|
+
appToken,
|
|
187
|
+
);
|
|
188
|
+
await new Promise<void>((resolve, reject) => {
|
|
189
|
+
const socket = new WebSocket(url);
|
|
190
|
+
const stop = () => {
|
|
191
|
+
socket.close();
|
|
192
|
+
resolve();
|
|
193
|
+
};
|
|
194
|
+
kit.signal.addEventListener('abort', stop, { once: true });
|
|
195
|
+
socket.addEventListener('message', (message) => {
|
|
196
|
+
const envelope = JSON.parse(String(message.data)) as Envelope;
|
|
197
|
+
if (envelope.envelope_id)
|
|
198
|
+
socket.send(JSON.stringify({ envelope_id: envelope.envelope_id }));
|
|
199
|
+
if (envelope.type === 'disconnect') return socket.close();
|
|
200
|
+
void handle(envelope).catch((error: unknown) =>
|
|
201
|
+
kit.status(
|
|
202
|
+
`couldn't handle a Slack event: ${error instanceof Error ? error.message : String(error)}`,
|
|
203
|
+
),
|
|
204
|
+
);
|
|
205
|
+
});
|
|
206
|
+
socket.addEventListener('close', () => {
|
|
207
|
+
kit.signal.removeEventListener('abort', stop);
|
|
208
|
+
if (!kit.signal.aborted) reject(new Error('Slack closed the connection'));
|
|
209
|
+
});
|
|
210
|
+
socket.addEventListener('error', () =>
|
|
211
|
+
reject(new Error('Slack connection failed')),
|
|
212
|
+
);
|
|
213
|
+
});
|
|
214
|
+
},
|
|
215
|
+
invite: (code) =>
|
|
216
|
+
`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})` : ''}`,
|
|
217
|
+
deliver: async (reply, to) => {
|
|
218
|
+
const channel = chatFor(to);
|
|
219
|
+
await post(channel, reply);
|
|
220
|
+
for (const file of reply.files ?? [])
|
|
221
|
+
await slack.upload(botToken, channel, file.path, file.caption);
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
},
|
|
225
|
+
});
|